Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct in LINQ-C#

Tags:

c#

linq

I have the below list and query expression to get the distinct list.

 List<LinqTest> myList = new List<LinqTest>();
 myList.Add(new LinqTest() { id = 1, value = "a" });
 myList.Add(new LinqTest() { id = 1, value = "b" });
 myList.Add(new LinqTest() { id = 2, value = "c" });
 myList.Select(m => new { m.id}).Distinct().ToList();

I have referred the below SO link linkfor the code. Even after using distinct() i'm getting 3 records with the duplicate values. what could be the reason?

like image 980
user1357872 Avatar asked May 30 '17 04:05

user1357872


People also ask

What does distinct do in 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).

Why distinct is not working in LINQ?

Yes, it doesn't work as expected! This is because the Distinct method uses the default equality comparer to compare the values under the hood. Since we are dealing with reference type object, the Distinct() method will treat the values as unique even if the property values are the same.

Is distinct a set operator?

The Distinct operator returns the set which does not contain duplicate values. Or in other words, we can say that this operator removes all the duplicate values from the set or collection and return a set or collection which contain unique or dissimilar values.


2 Answers

The 3 records that you see at debug time is your existing list. I think all that you've missed is an assignment.

List<LinqTest> myList = new List<LinqTest>();
myList.Add(new LinqTest() { id = 1, value = "a" });
myList.Add(new LinqTest() { id = 1, value = "b" });
myList.Add(new LinqTest() { id = 2, value = "c" });
// not sure why new {m.id} was used in this context
List<int> distinctList = myList.Select(m => m.id).Distinct().ToList();
like image 74
touchofevil Avatar answered Oct 16 '22 12:10

touchofevil


In your case the Distinct() method uses the default equality comparer of anonimous type object. Therefore the result is not expected. If you want to get unique id values use

List<int> ListOfIDs = myList.Select(m => m.id).Distinct().ToList();

If you want to get distinct objects of a custom type, then you need to implement IEquatable generic interface and provide your own GetHashCode and Equals methods for the type. See MSDN for details.

like image 5
Alexander Avatar answered Oct 16 '22 11:10

Alexander