Search code examples
asp.netlinqentity-framework-5where-clause

How to select distinct based on combination of two fields with LINQ?


How can I select only the records that have a distinct combination of only two values in a row?

For instance, say I have the following:

Name     |     Age     |     Height
------------------------------------
Joe          19               99
Kim          19               76
Joe          20               88
Joe          19               69

How could I write a LINQ expression to select only the rows with the same Name AND Age?

I tried: var count = context.people.Where(p => (p.age && p.name).Distinct()); and var count = context.people.Where(p => (p.age.Distinct() && p.name.Distinct()));

What's the right way to do this?


Solution

  • You can select just the name and age into an anonymous type, and then use Distinct():

    var results = context.people
                         .Select(p => new { p.Name, p.Age })
                         .Distinct();
    

    Obviously that won't give you the height, but then there is no single height. If you want all the heights as well, you need to group instead:

    var results = context.people
                         .GroupBy(p => new { p.Name, p.Age });
    

    That will give you a sequence of groupings, where each grouping contains all the people with the same name and age.