Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing 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;
        }

its is giving compile time error . I know that we can do this with Lambda expression like this. a.OrderBy(s=>s.Length).ToArray(); but i want to this do by defining different function . What mistake i have done?

like image 499
freak Avatar asked Mar 05 '26 19:03

freak


1 Answers

The expression fun is an untyped expression called a method group.
Since a method group has no type, the compiler cannot infer the type parameters of the generic OrderBy method.

You need to explicitly pass the type parameters, like this:

a = a.OrderBy<string, int>(fun).ToArray();

Or,

a = a.OrderBy(new Func<string, int>(fun)).ToArray();
like image 83
SLaks Avatar answered Mar 08 '26 08:03

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!