How to get an object from a list based upon IEqualityComparer<T>

Posted by Greg on Stack Overflow See other posts from Stack Overflow or by Greg
Published on 2010-05-07T20:47:57Z Indexed on 2010/05/07 20:58 UTC
Read the original article Hit count: 249

Filed under:
|

The Compare method in Linq lets you find by an IEqualityComparer, but I can't find a counterpart method that allows you retrieve an item by the same comparer.

Is this really the best way to do it?

MyItem myFinderItem = new MyItem(keyField1, keyField2);
if (myList.Contains(myFinderItem, new MyEqualityComparer()))
{
    MyItem myRealItem = myList.Single(item => new MyEqualityComparer().Equals(item , myFinderItem));
}

(I'm sharing the usage of the IEqualityComaprer with a call to the Except Linq method and I'd like to maintain a single source for equality comparisons)

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about c#