Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 516
Athena Avatar asked Dec 15 '22 06:12

Athena


2 Answers

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()
like image 81
Henrik Ilgen Avatar answered Dec 27 '22 06:12

Henrik Ilgen


Distinct() returns a brand new IEnumerable, so:

var result = 
  As.
    Distinct(new AsComparer()).
    OrderBy(e => e.Test).
    ToList();
like image 36
Anton Gogolev Avatar answered Dec 27 '22 05:12

Anton Gogolev