none
LINQ Select Distinct Sorted Using Group C# RRS feed

  • Question

  • Suppose I have an unsorted table like this:

    RecordID Product BrewDate Batch
    4417 IPA 10/29/2013 74
    4395 IPA 10/28/2013 74
    4573 IPA 10/27/2013 75

    ...

    I am trying to create a LINQ to EF query in C# that will return a list of records that have a distinct Batch # and most recent date.

    I can get it to work correctly using Distinct and IEqualityComparer but I read that it is inefficient since it grabs all the data in the table which in this case is very large.

    I want to use grouping like this:

    var distinctQuery = from x in MyDatabase.BeerTable                                    
                                 group x by x.Batch
                                 into uniqueBatches 
                                 select uniqueBatches.FirstOrDefault();

    distinctQuery = distinctQuery.OrderByDescending(x => x.Batch);

    This works but its getting the wrong distinct records; it gets 4395 when I want 4417.  How do I tell the group to sort based on date before it picks FirstOrDefault?


    -7

    Tuesday, February 11, 2014 10:49 PM

Answers

  • Hello,

    >>How do I tell the group to sort based on date before it picks FirstOrDefault?

    Have a try this:

    select uniqueBatches.OrderByDescending(u => u.BrewDate).FirstOrDefault();

    The result:

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by smyrin Wednesday, February 12, 2014 5:53 PM
    Wednesday, February 12, 2014 4:12 AM
    Moderator