I'm trying to remove duplicates from a list using a custom equality comparer, but I can't seem to get it right.
Simplified example:
class A
{
public A(string Test) { this.Test = Test; }
public string Test;
public string ToString() { return Test; }
}
class AsComparer: EqualityComparer<A>
{
public override bool Equals(A x, A y)
{
return (x.Test == y.Test);
}
public override int GetHashCode(A obj)
{
return obj.Test.GetHashCode();
}
}
static private void Test()
{
var As = new List<A> { new A("Test1"), new A("Test3"), new A("Test1"), new A("Test2") };
As.Distinct(new AsComparer());
As.Sort((e1, e2) => { return (e1.Test.CompareTo(e2.Test)); });
}
This returns the collection "Test1", "Test1", "Test2", "Test3". I want there to be only one "Test1", but can't seem to figure out how to do this right.
Any ideas?
Distinct
returns an IEnumerable<T>
, it does not operate on the source list itself. You'll have to do:
As = As.Distinct(new AsComparer()).ToList()
You can also include your sorting here:
As = As
.Distinct(new AsComparer())
.OrderBy(x => x.Test)
.ToList()
Distinct()
returns a brand new IEnumerable
, so:
var result =
As.
Distinct(new AsComparer()).
OrderBy(e => e.Test).
ToList();
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