Kevin
Kevin

Reputation: 1950

Selecting only unique values from collection

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

Upvotes: 1

Views: 1900

Answers (2)

Robert Christ
Robert Christ

Reputation: 2230

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.

Upvotes: 1

Jeff Mercado
Jeff Mercado

Reputation: 134611

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());

Upvotes: 2

Related Questions