1

I got the code below from here

    var distinctAllEvaluationLicenses = allEvaluationLicenses.GroupBy((License => 
License.dateCreated)).Select(License => License.First());

How can I select the latest 'dateCreated' instead of the First one?

Community
  • 1
  • 1
Mikk
  • 455
  • 1
  • 13
  • 19

2 Answers2

3

If all you want is the max dateCreated, try this:

var results = allEvaluationLicenses.Max(x => x.dateCreated);

If you want the licenses with the max dateCreated, try this:

var results =
    allEvaluationLicenses.GroupBy(x => x.dateCreated)
                         .OrderByDescending(g => g.Key)
                         .First();

Or in query syntax:

var results =
    (from l in allEvaluationLicenses
     group l by l.dateCreated into g
     orderby g.Key descending
     select g)
    .First();
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
1

You can use Max to get the largest of a sequence.

var distinctAllEvaluationLicenses = allEvaluationLicenses.GroupBy(License => 
License.dateCreated)
    .Max(group => group.Key);

That said, in this particular context, there doesn't seem to be any reason to do the grouping at all:

var distinctAllEvaluationLicenses = allEvaluationLicenses
    .Max(License=> License.dateCreated)
Servy
  • 202,030
  • 26
  • 332
  • 449
  • This doesn't seem to be what the OP wants, in that you are getting the Date; the OP seems to want the group of License objects that corresponds to the date. – NominSim Apr 29 '13 at 16:22
  • Thanks Servy. I had to group them because the database wasn't designed well hence there are duplicates where the only difference is the datecreated so I had get the latest one – Mikk Apr 29 '13 at 16:40