2

Note this question is similar this one except I'm not working with linq-to-sql, so the "let" is not usable.

Basically I have a select of the type

... .Select(c => new SampleClass { Id = c.Location.Name, Name = c.Location.Name }).Distinct().ToList()

which used to work when I just had

... .Select(c => c.Location.Name).Distinct().ToList()

How would I make a distinct call on one of the items within the SampleClass?

Community
  • 1
  • 1
Rio
  • 14,182
  • 21
  • 67
  • 107

2 Answers2

3

You can group items by the key, and then select what item from the group you want to use as value. I use FirstOrDefault as an example:

... .Select(c => new SampleClass { Id = c.Location.Name, Name = c.Location.Name })
    .GroupBy(c => c.Id)
    .Select(group => group.FirstOrDefault())
    .ToList()
Sander Rijken
  • 21,376
  • 3
  • 61
  • 85
0

Is this what you need: http://sprokhorenko.blogspot.com/2009/11/convenient-distinct.html ?

This is an extension for IEnumerable that allows you to .Distinct() for any field (or even several ones using lambdas), which creates IEqualityComparer for you on the fly.

queen3
  • 15,333
  • 8
  • 64
  • 119
  • i almost voted you down for the external link ( i hate it to find a question with an answer and then not to be able to follow the links ), but since that link is actually Awesome, i didnt vote down. – Rafael Herscovici Aug 22 '11 at 11:43
  • 1
    OK, I'll keep that in mind for future. Thanks for the kind words, I'm glad my blog was useful for someone. Maybe it's time to continue writing ;-) – queen3 Sep 08 '11 at 15:21
  • 1
    The approach described in the linked post is what I also prefer. I wonder why this extension method isn't included in the framework out-of-the-box, as it kinda jumps into your face once you have to deal with Distinct(). – alexander.biskop Mar 14 '13 at 13:29
  • External link is dead – briddums Dec 12 '18 at 02:44