Linq select Distinct by two properties

c#, distinct, linq, linq-to-entities

Solution

You can use grouping, as much as it makes me cringe to use groupBy to do a distinct. You can just call `First` on the `IGrouping` to get one item out of the group, which is in effect a distinct. It will look something like this:

var distinctItems = data.GroupBy(item => new{
  //include all of the properties that you want to 
  //affect the distinct-ness of the query
  item.Property1
  item.Property2
  item.Property3
})
.Select(group => group.Key);
//if it's important that you have the low rank use the one below.
// if you don't care use the line above
//.Select(group => group.Min(item => item.Rank));

Problem

I have a fairly complex LINQ query that joins several tables, and selects a new anonymous type that is three IEnumerable's `{Users, JobProviders, Jobs}`. It returns an IQueryable to maintain deferred execution, which eliminates DistintBy from this question. One of the columns is a rank, and I need to make sure that only the record with the lowest rank for each job (another column, many jobs will get selected) gets selected. Distinct doesn't work because the rank will obviously make the row unique. I thought the group clause might help this, but it changes the return type to IGrouping. I don't fully understand how group works, so I may be wrong, but it looks it wont work. Is there any way to say for each job, take only the lowest rank? something like ``` let jobRank = JobProvider.Rank ...where min(rank) ```

Original source

Related problems