I have the following code:
var foo = (from data in pivotedData.AsEnumerable()
select new
{
Group = data.Field<string>("Group_Number"),
Study = data.Field<string>("Study_Name")
}).Distinct();
As expected this returns distinct values. However, what I want is to return a strongly-typed collection as opposed to an anonymous type, so when I do:
var foo = (from data in pivotedData.AsEnumerable()
select new BarObject
{
Group = data.Field<string>("Group_Number"),
Study = data.Field<string>("Study_Name")
}).Distinct();
This does not return the distinct values, it returns them all. Is there a way to do this with actual objects?
For
Distinct()(and many other LINQ features) to work, the class being compared (BarObjectin your example) must implement implementEquals()andGetHashCode(), or alternatively provide a separateIEqualityComparer<T>as an argument toDistinct().Many LINQ methods take advantage of
GetHashCode()for performance because internally they will use things like aSet<T>to hold the unique items, which uses hashing for O(1) lookups. Also,GetHashCode()can quickly tell you if two objects may be equivalent and which ones are definitely not – as long asGetHashCode()is properly implemented of course.So you should make all your classes you intend to compare in LINQ implement
Equals()andGetHashCode()for completeness, or create a separateIEqualityComparer<T>implementation.