Use Group By in order to remove duplicates
c#, collections, duplicates, linq
Solution
people
.GroupBy(p => p.Name)
.Select(g => g.OrderByDescending(p => p.Age).First())
This will work across different Linq providers. If this is just Linq2Objects, and speed is important (usually, it isn't) consider using one of the many MaxBy extensions found on the web (here's Skeet's) and replacing
g.OrderByDescending(p => p.Age).First()
with
g.MaxBy(p => p.Age)
Problem
I am looking for a simple way of removing duplicates without having to implement the class IComparable, having to override GetHashCode etc.. I think this can be achieved with linq. I have the class: ``` class Person { public string Name; public ing Age; } ``` I have a list of about 500 People `List<Person> someList = new List<Person()` now I want to remove people with the same name and if there is a duplicate I want to keep the person that had the greater age. In other words if I have the list: ``` Name----Age--- Tom, 24 | Alicia, 22 | Alicia, 12 | ``` I will like to end up with: ``` Name----Age--- Tom, 24 | Alicia, 22 | ``` How can I do this with a query? My list is not that long so I don't want to create a hash set nor implement the IComparable interface. It will be nice if I can do this with a linq query. I think this can be done with the groupBy extension method by doing something like: ``` var people = // the list of Person person.GroupBy(x=>x.Name).Where(x=>x.Count()>1) ... // select the person that has the greatest age... ```