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.
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);
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.
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