我有以下方法:
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
之外,调用总是相同的,所以对于没有重复的代码,我想要类似的东西:< / p>
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);
我不确定是否有可能,但如果是这样,如何实现这一目标?我不想重复代码。
答案 0 :(得分:4)
是的,您可以将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);
答案 1 :(得分:1)
首先声明lambda变量:
Func<CustomType, string> lambdaExpresion;
在switch
陈述之前。这是可能的,因为在两种情况下λ的类型都是相同的;否则就不可能。
答案 2 :(得分:1)
您可以定义一个变量来保存您的函数,
Func<CustomType, string> lambdaExpresion;
然后在switch
块中分配,就像这样,
switch (sortBy)
{
case "name":
lambda = s => s.Name;
break;
case "surname":
lambda = s => s.Surname;
break;
}
答案 3 :(得分:0)
你基本上已经在那里了:
Func<CustomType, string> lambdaExpresion;
switch (sortBy)
{
case "name":
lambdaExpresion = s => s.Name.ToString();
break;
case "surname":
lambdaExpresion = s => s.Surname.ToString();
break;
case default: //need a default value for it to be definitely assigned.
lambdaExpresion = s => "";
}
orderedList = this.Sort(lstCustomTypes, lambdaExpresion,
direction == "ASC" ? SortDirection.Ascending : SortDirection.Descending);
答案 4 :(得分:0)
好的,以防万一没有人使用反射:)
orderedList = this.Sort<CustomType, string>(
lstCustomTypes,
s => s.GetType().GetProperty(sortBy).GetValue(s).Tostring(),
direction == "ASC" ? SortDirection.Ascending : SortDirection.Descending);
请注意不存在的道具或字段,不兼容的名称(就像您可能希望将第一个字母大写一样)。错误检查左边是一个例外(因为我现在没有一个盒子来测试这段代码)
答案 5 :(得分:0)
你已经得到了正确答案。但是,也许你应该只使用OrderBy和OrderByDescending:
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.orderby.aspx
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.orderbydescending.aspx
来自第一个链接的示例:
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
IEnumerable<Pet> query = pets.OrderBy(pet => pet.Age);