Linq select Distinct with two properties

I have a rather complicated LINQ query that joins several tables and selects a new anonymous type, which is three IEnumerable {Users, JobProviders, Jobs}. It returns IQueryable to support deferred execution, which removes DistintBy from this issue .

One of the columns is the rank, and I need to make sure that only the record with the lowest rank for each task is selected (another column, many tasks will be selected). The difference does not work, because the rank will obviously make the string unique.

I thought a group suggestion might help with this, but it changes the return type to IGrouping. I don’t quite understand how the group works, so I could be wrong, but it doesn’t seem to work. Is there a way to say for each job, take only the lowest rank?

sort of

let jobRank = JobProvider.Rank
...where min(rank)
+3
source share
2 answers

You can use grouping, as it makes me cringe to use groupBy to make it separate. You can simply call Firstin IGroupingto get one item from the group, which is actually separate. 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 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));
+4
source

Good solution here:

LINQ's Distinct () for a specific property

, "". , LINQ, :

What you need is a "distinct-by" effectively. I don't believe it part of LINQ as it stands, although it fairly easy to write:

public static IEnumerable<TSource> DistinctBy<TSource, TKey>
    (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    HashSet<TKey> seenKeys = new HashSet<TKey>();
    foreach (TSource element in source)
    {
        if (seenKeys.Add(keySelector(element)))
        {
            yield return element;
        }
    }
}
+2

All Articles