Pass Func <TSource, TKey> keySelector error
static void Main() { string[] a = { "a", "asd", "bdfsd", "we" }; a = a.OrderBy(fun).ToArray(); } private static int fun(string s) { return s.Length; } it gives a compile-time error. I know that we can do this using the Lambda expression as follows. a.OrderBy(s=>s.Length).ToArray(); but I want to do this by defining another function. What mistake did I make?
The fun expression is an untyped expression called a group of methods.
Since the group of methods has no type, the compiler cannot infer parameters of the type of the general OrderBy method.
You need to explicitly pass type parameters, for example:
a = a.OrderBy<string, int>(fun).ToArray(); Or
a = a.OrderBy(new Func<string, int>(fun)).ToArray(); SLaks is true that the C # 3 compiler will not allow this, but it is important to indicate that the C # 4 compiler will compile your example without any problems.
Here is what happened. When I first applied the method type inference algorithm for C # 3, I reasoned, since SLaks suggests: groups of methods have no type, they were not deduced from them in C # 2, and to resolve the overload, you must select a method from the group of methods, knowing types of arguments that we are trying to make; this is a problem with chicken and egg. I wrote about this in November 2007:
There was so much response to this that we decided to review the problem and change the type inference algorithm so that we can draw conclusions from the groups of methods, provided that a sufficient number of conclusions have already been made that the resolution of the overload can continue in the group of methods.
Unfortunately, this change happened too late in the loop and did not end up in C # 3. We moved it to C # 4, and there you go.
I wrote about this in 2008:
http://blogs.msdn.com/ericlippert/archive/2008/05/28/method-type-inference-changes-part-zero.aspx