Athena Athena - 1 month ago 7
C# Question

Uniquifying a list (C#)

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?

Answer

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()
Comments