Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a distinct list from a List of objects?

I have a List<MyClass> someList.

class MyClass {     public int Prop1...     public int Prop2...     public int Prop3... } 

I would like to know how to get a new distinct List<MyClass> distinctList from List<MyClass> someList, but only comparing it to Prop2.

like image 865
Willem Avatar asked Feb 14 '11 11:02

Willem


People also ask

What is distinct Linq?

C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).


1 Answers

You can emulate the effect of DistinctBy using GroupBy and then just using the first entry in each group. Might be a bit slower that the other implementations though.

someList.GroupBy(elem=>elem.Prop2).Select(group=>group.First()); 
like image 183
CodesInChaos Avatar answered Oct 11 '22 09:10

CodesInChaos