1

I have a collection of user objects, but need to return a list of distinct users based on User ID.

So I'm wondering is it possible to select only distinct values based on a given property of the user object?

Collection<User> users = serializer.Deserialize<Collection<User>>(userCollection);

User Object:

UserID
UserName

Thanks

Kevin
  • 1,940
  • 3
  • 24
  • 38
  • What is your collection object? System.Collections.ObjectModel.Collection or something else? – goric Aug 24 '12 at 15:41
  • 1
    possible duplicate of [Distinct by property of class by linq](http://stackoverflow.com/questions/2537823/distinct-by-property-of-class-by-linq) – Jon Skeet Aug 24 '12 at 15:43
  • Checkout this post detailing the same issue: http://stackoverflow.com/questions/568347/how-do-i-use-linq-to-obtain-a-unique-list-of-properties-from-a-list-of-objects Hope this helps! – N. Taylor Mullen Aug 24 '12 at 15:41

2 Answers2

2

Use morelinq's DistinctBy() method.

var distinctUsers = users.DistinctBy(user => user.UserID);

Or craft the query on your own by grouping on what you want to get the distinction and take the first item in the group.

var distinctUsers = users.GroupBy(user => user.UserID)
                         .Select(g => g.First());
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
1

This could be solved via the use of a Hashset quite easily. To do this, simply ensure that your User class has an override for both Equals and GetHashCode, and you should be set.

Edit: as DavidM mentions below, overriding equals and gethashcode for a class is only worth it if this is the normal comparison case for User objects. If not, then Hashsets can be instantiated with custom comparers, and I would suggest going this method.

Robert Christ
  • 1,910
  • 2
  • 13
  • 19
  • Overriding its Equals and GetHashCode implementations just for one use case doesn't sound like a good idea to me... – David M Aug 24 '12 at 15:41
  • @DavidM fair point, but if this isn't the normal comparison case, then just use a custom comparer when instantiating the hashset. – Robert Christ Aug 24 '12 at 15:42
  • Yes, exactly. If you edit this in then that's worth a +1 from me... :) – David M Aug 24 '12 at 15:44