Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Func<T, TResult> access parameter

Tags:

c#

I'm creating an extension method:

public static IEnumerable<T> GroupAndSortBy<T>(this IEnumerable<T> source)

I would like to call this method from any collection:

myCollection.GroupAndSortBy(x => x.MyParam)

Where MyParam must be a string, because I want to use this in the method for alphabetic grouping.

Doing this, I should change the method signature to this:

public static IEnumerable<T> GroupAndSortBy<T>(this IEnumerable<T> source, Func<T, string> key)

The problem is that now I can't access the actual string that I'm passing as parameter, but I would like to do something like this:

source.GroupBy(key.ToLower().FirstOrDefault());

Can you help me?

like image 505
xTuMiOx Avatar asked Sep 28 '26 01:09

xTuMiOx


1 Answers

Since key is a delegate, you should be invoking it, like this:

source.GroupBy(t => key(t).ToLower().FirstOrDefault());

This tells LINQ that in order to obtain a group key from a source value t of type T one needs to invoke key(t), convert it to lower case, and grab the first letter, if any.

Note: You do not need to convert the whole key to lower case if all you want is the first letter:

source.GroupBy(t => char.ToLower(key(t).FirstOrDefault()));
like image 117
Sergey Kalinichenko Avatar answered Sep 30 '26 16:09

Sergey Kalinichenko