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?
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With