gpt4 book ai didi

c# - 如何使用 lambda 表达式作为参数?

转载 作者:行者123 更新时间:2023-11-30 14:33:15 26 4
gpt4 key购买 nike

我有以下方法:

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

根据情况,参数 Func<TSource,TKey>更改,例如,我有以下开关:

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

因此,正如您在这些情况下观察到的那样,调用始终相同,除了 lambda 参数 s => something。 , s => something2所以对于没有重复的代码,我想要类似的东西:

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

我不确定这是否可能,但如果可以,如何实现呢?我不想重复代码。

最佳答案

是的,您可以将 lambda 赋给一个变量:

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

关于c# - 如何使用 lambda 表达式作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16821143/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com