I am using distinct which says
Returns distinct elements from a sequence by using the default
equality comparer to compare values.
Yet when I run this code, I get multiple same id’s
var ls = ls2.Distinct().OrderByDescending(s => s.id);
foreach (var v in ls)
{
Console.WriteLine(v.id);
}
I implemented these in my class yet this still doesnt work
class Post : IComparable<Post>, IEqualityComparer<Post>, IComparer<Post>
This is how I implemented it
int IComparable<Post>.CompareTo(Post other)
{
return (int)(id - other.id);
}
bool IEqualityComparer<Post>.Equals(Post x, Post y)
{
return x.id == y.id;
}
int IEqualityComparer<Post>.GetHashCode(Post obj)
{
throw new NotImplementedException();
}
int IComparer<Post>.Compare(Post x, Post y)
{
return (int)(x.id - y.id);
}
You need to properly implement
GetHashCode()in your comparer – in your case you can just return the hash code of the id:Also as pointed out by @dash in a comment you need to implement
IEquatable<T>inPostif you choose to go that route (option 1).A comparer should be implemented in a separate class that you can then pass in in one of the
Distinct()overloads (option 2), i.e. in your case could be classMyPostComparer:A third option would be to use the
DistinctBy()method of the MoreLinq project.