9

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)

Edit: What I'm looking for a method that has the signature:

T Find<T>(T t, IEqualityComparer<T> comparer)

Edit2: I guess this works, it's funky. but it's horrible and would never use it:(

myList.Intersect( new List<MyItem>{myFinderItem}, comparer).Single();
Greg
  • 16,540
  • 9
  • 51
  • 97
  • What behavior do you expect if the element isn't found? – Roman May 07 '10 at 21:14
  • @R0MANARMY: Doesn't really matter to me, either return null or throw would be fine. – Greg May 07 '10 at 21:22
  • You might also be interested in this question (difference between using `Single` and using `First`) http://stackoverflow.com/questions/2724096/linq-single-vs-first – Roman May 07 '10 at 21:29
  • I should down-vote you for your second edit, that's all kinds of wrong (mostly because it obscures the intent). – Roman May 07 '10 at 21:31
  • Lol, you're absolutely right! I struck the Edit2 to make it less downvote worthy. – Greg May 07 '10 at 21:32

1 Answers1

10

First, you should use the same instance of MyEqualityComparer rather than creating a new instance every time (you should perhaps consider making it a singleton).

Other than that, I don't think there's a much better way of doing it. If you want to make it shorter and more readable, you could create an extension method that takes a IEquaityComparer<T> instead of a predicate :

public static T Single<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer, T value)
{
    return source.Single(item => comparer.Equals(item, value));
}
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • All around good advice that gets me to a cleaner solution. I guess the final answer is "it doesn't exist, make your own". – Greg May 07 '10 at 21:26