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.
In case if you need this function for use with lambda and possibly two different element types:
I was also googling the web for a solution, but i didn't found any satisfying one. So i've created a generic EqualityComparerFactory:
The idea is, that the CreateComparer method takes two arguments: a delegate to GetHashCode(T) and a delegate to Equals(T,T)
Example:
These methods don't have overloads that accept a delegate instead of an interface, but:
Enumerable.OrderBy
Enumerable.Select
before callingEnumerable.SequenceEqual
IEqualityComparer<T>
in terms ofFunc<T, T, bool>
You can't pass it directly however you could do so by defining a
LambdaComparer
class that excepts aFunc<T,T,int>
and then uses that in it'sCompareTo
.It is not quite as concise but you could make it shorter through some creative extension methods on
Func
.I vote for the dreaming theory.
You can't pass a function where an object is expected: derivatives of System.Delegate (which is what lambdas are) don't implement those interfaces.
What you probably saw is a use of the of the
Converter<TInput, TOutput>
delegate, which can be modeled by a lambda. Array.ConvertAll uses an instance of this delegate.You can provide a lambda for a Array.Sort method, as it requires a method that accepts two objects of type T and returns an integer. As such, you could provide a lambda of the following definition
(a, b) => a.CompareTo(b)
. An example to do a descending sort of an integer array: