Pass a lambda expression in place of IComparer or IEqualityComparer or any single-method interface?

Water Cooler v2 picture Water Cooler v2 · Jul 6, 2010 · Viewed 52.1k times · Source

I happened to have seen some code where this guy passed a lambda expression to a ArrayList.Sort(IComparer here) or a IEnumerable.SequenceEqual(IEnumerable list, IEqualityComparer here) where an IComparer or an IEqualityComparer was expected.

I can't be sure if I saw it though, or I am just dreaming. And I can't seem to find an extension on any of these collections that accepts a Func<> or a delegate in their method signatures.

Is there such an overload/extension method? Or, if not, is it possible to muck around like this and pass an algorithm (read delegate) where a single-method interface is expected?

Update Thanks, everyone. That's what I thought. I must've been dreaming. I know how to write a conversion. I just wasn't sure if I'd seen something like that or just thought I'd seen it.

Yet another update Look, here, I found one such instance. I wasn't dreaming after all. Look at what this guy is doing here. What gives?

And here's another update: Ok, I get it. The guy's using the Comparison<T> overload. Nice. Nice, but totally prone to mislead you. Nice, though. Thanks.

Answer

Xose Lluis picture Xose Lluis · Jun 11, 2012

I'm not much sure what useful it really is, as I think for most cases in the Base Library expecting an IComparer there's an overload that expects a Comparison... but just for the record:

in .Net 4.5 they've added a method to obtain an IComparer from a Comparison: Comparer.Create

so you can pass your lambda to it and obtain an IComparer.