kez
kez

Reputation: 2313

Sort linq query result, when it has "First() and into Group"

var qryLatestInterview = from rows in dt.AsEnumerable()                                     
                         group rows by new 
                         { 
                           PositionID = rows["msbf_acc_cd"], 
                           CandidateID = rows["msbf_fac_tp"] 
                         } into grp
                         select grp.First();

I want to sort by above results using msbf_fac_dt which is a DateTime Column,

So I did following changes

var qryLatestInterview = from rows in dt.AsEnumerable()
                         orderby rows["msbf_fac_dt"] ascending
                         group rows by new 
                         {
                           PositionID = rows["msbf_acc_cd"], 
                           CandidateID = rows["msbf_fac_tp"], 
                           FacilityDate = rows["msbf_fac_dt"] 
                         } into grp
                         select grp.First();

But this is not sort by above msbf_fac_dt column , what can I do here

Upvotes: 1

Views: 405

Answers (2)

Hari Prasad
Hari Prasad

Reputation: 16966

If I understand correctly, you want to get recent facilitated record from this list, you could do ordering after grouping and take first record.

dt.AsEnumerable()
  .GroupBy(row => new 
   { 
         PositionID = rows["msbf_acc_cd"], 
         CandidateID = rows["msbf_fac_tp"]
   })
  .Select(x=>x.OrderByDescending(o=>o["msbf_fac_dt"]>).FirstOrDefault() 
  .ToList();

Upvotes: 0

Zein Makki
Zein Makki

Reputation: 30052

You can order the group before selecting the first record:

var qryLatestInterview = from rows in dt.AsEnumerable()
                         group rows by new
                         {
                             PositionID = rows["msbf_acc_cd"],
                             CandidateID = rows["msbf_fac_tp"],
                         } into grp
                         select grp.OrderBy(x=> x["msbf_fac_dt"]).First();

Upvotes: 2

Related Questions