How to get an object from a list based on IEqualityComparer <T>
The Linq comparison method allows you to find IEqualityComparer, but I cannot find the counterparty method that allows you to get an element with the same mapping.
Is this really the best way to do this?
MyItem myFinderItem = new MyItem(keyField1, keyField2); if (myList.Contains(myFinderItem, new MyEqualityComparer())) { MyItem myRealItem = myList.Single(item => new MyEqualityComparer().Equals(item , myFinderItem)); } (I am using IEqualityComaprer with the Except Linq method call, and I would like to support a single source for comparing equalities)
Edit: what I'm looking for for a method that has a signature:
T Find<T>(T t, IEqualityComparer<T> comparer) Edit2: I think it works, it's funky . but it is terrible and will never use it :(
myList.Intersect( new List<MyItem>{myFinderItem}, comparer).Single(); First, you should use the same instance of MyEqualityComparer , and not create a new instance each time (maybe you should consider making it single).
Other than that, I don't think there is a much better way to do this. If you want to make it shorter and more readable, you can create an extension method in which instead of <predicate instead of IEquaityComparer<T> :
public static T Single<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer, T value) { return source.Single(item => comparer.Equals(item, value)); }