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?
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).
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.
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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With