Tell LINQ Distinct which item to return

Posted by Jon on Stack Overflow See other posts from Stack Overflow or by Jon
Published on 2010-03-30T13:24:46Z Indexed on 2010/03/30 13:33 UTC
Read the original article Hit count: 384

Filed under:
|
|
|
|

I understand how to do a Distinct() on a IEnumerable and that I have to create an IEqualityComparer for more advanced stuff however is there a way in which you can tell which duplicated item to return?

For example say you have a List<T>

List<MyClass> test = new List<MyClass>();
test.Add(new MyClass {ID = 1, InnerID = 4});
test.Add(new MyClass {ID = 2, InnerID = 4});
test.Add(new MyClass {ID = 3, InnerID = 14});
test.Add(new MyClass {ID = 4, InnerID = 14});

You then do:

var distinctItems = test.Distinct(new DistinctItemComparer());

class DistinctItemComparer : IEqualityComparer<MyClass> {

    public bool Equals(MyClass x, MyClass y) {
        return x.InnerID  == y.InnerID;;
    }

    public int GetHashCode(MyClassobj) {
        return obj.InnerID.GetHasCode();
    }
}

This code will return the classes with ID 1 and 3. Is there a way to return the ID matches 2 & 4.

© Stack Overflow or respective owner

Related posts about c#

Related posts about c#3.0