1

In this code snippet how do I use distinct feature only for e.EntityNumber while selecting all the other values [ e.Firstname, e.Surname, e.EntityNumber ].

response
   .Categories
   .SelectMany(c => c.Events)
   .Select(e => new { e.Firstname, e.Surname, e.EntityNumber })
   .Distinct()
   .ToList()
BrunoLM
  • 97,872
  • 84
  • 296
  • 452
Soni
  • 425
  • 2
  • 6
  • 18
  • Also see [Why is there no Linq method to return distinct values by a predicate?](http://stackoverflow.com/questions/520030/why-is-there-no-linq-method-to-return-distinct-values-by-a-predicate) – Yaseen Dec 21 '13 at 04:25

2 Answers2

3

You can use GroupBy instead:

response
   .Categories
   .SelectMany(c => c.Events)
   .Select(e => new { e.Firstname, e.Surname, e.EntityNumber })
   .GroupBy(x => x.EntityNumber)
   .Select(grp => grp.First())
   .ToList()

I have selected an arbitrary row of each group (the first). You can change grp.First() according to your logic.

//...
.GroupBy(x => x.EntityNumber)
.Select(grp => grp.OrderBy(x => /* Insert logic here */).First())
//...
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

You can implement an extension method DistinctBy

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, 
    Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer = null)
{
    if (source == null) throw new ArgumentNullException("source");
    if (keySelector == null) throw new ArgumentNullException("keySelector");

    var keys = new HashSet<TKey>(comparer);
    foreach (var element in source)
    {
        if (keys.Add(keySelector(element)))
        {
            yield return element;
        }
    }
}
BrunoLM
  • 97,872
  • 84
  • 296
  • 452