Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a lambda expression as a parameter?

Tags:

c#

lambda

linq

I have below method:

private List<TSource> Sort<TSource, TKey>(
    List<TSource> list, 
    Func<TSource, TKey> sorter, 
    SortDirection direction)
{
    ...
}

and depending on the case, the parameter Func<TSource,TKey> changes, for example, I have following switch:

public class CustomType
{
    string Name {get; set;}
    string Surname {get; set;}
    ...
}

switch (sortBy)
{
    case "name":
        orderedList = this.Sort<CustomType, string>(
            lstCustomTypes,
            s => s.Name.ToString(),
            direction == "ASC" ? SortDirection.Ascending : SortDirection.Descending);
        break;
    case "surname":
        orderedList = this.Sort<CustomType, string>(
            lstCustomTypes,
            s => s.Surname.ToString(),
            direction == "ASC" ? SortDirection.Ascending : SortDirection.Descending);
        break;
   }

so, as you can observe in those cases, the call is always the same except for the lambda parameter s => something, s => something2 so for no repeat code I would like to the something similar to:

switch (sortBy)
{
    case "name":
        lambdaExpresion = s => s.Name.ToString();
        break;
    case "surname":
        lambdaExpresion= s => s.Surname.ToString();
        break;
    }

    orderedList = this.Sort<CustomType, string>(
        lstCustomTypes,
        lambdaExpresion,
        direction == "ASC" ? SortDirection.Ascending : SortDirection.Descending);

I am not sure if it is possible, but if so how to achieve this? I do not want to repeat code.

like image 254
Ralph Avatar asked Dec 05 '25 14:12

Ralph


2 Answers

Yes, you can just assign the lambda to a variable:

Func<CustomType, string> lambda;  
switch (sortBy)
{
    case "name":
        lambda = s => s.Name.ToString();
        break;
    case "surname":
        lambda = s => s.Surname.ToString();
        break;
}

orderedList = this.Sort<CustomType, string>(
    lstCustomTypes,
    lambda,
    direction == "ASC" ? SortDirection.Ascending : SortDirection.Descending);
like image 186
Kenneth Avatar answered Dec 08 '25 02:12

Kenneth


Declare the lambda variable first:

Func<CustomType, string> lambdaExpresion;

Before the switch statement. This is possible because type of lambda in both cases are the same; otherwise it would not be possible.

like image 34
Kaveh Shahbazian Avatar answered Dec 08 '25 03:12

Kaveh Shahbazian



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!