Blendester
Blendester

Reputation: 1653

How to order the items of a list and remove duplicates based on a property?

I've this class:

public class User
{
    public long Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Username { get; set; }

    public int Contributions { get; set; }
}

My List<User> can contain multiple items with same Id but different Contributions value.

I want to have distinct values based on Id, but with the highest Contributions value for that Id. How can I do that? thanks.

I tried this but it's only a part of what I want:

list.OrderByDescending(x => x.Contributions);

Upvotes: 0

Views: 83

Answers (1)

qxg
qxg

Reputation: 7036

list.GroupBy(u => u.Id) // Distinct
    .Select(g => g.OrderByDescending(u => u.Contributions).First()); // Highest contributions

Upvotes: 6

Related Questions