减少(我的)Linq列表排序的详细程度
本文关键字:程度 排序 列表 我的 Linq 减少 | 更新日期: 2023-09-27 18:27:10
我有一个要排序的类型化DataTable,它就像:
DataTable.DefaultView.Sort("sortexpression");
因为排序表达式是一个字符串,所以无论我有多少排序选项,我都可以在几行中附加排序字段和方向。现在和林克在一起,我显然做了一些非常错误的事情,因为为了做类似的事情,我正在做:
this.GetSortExpressions();
if ((ViewState["SortDirection"] as string) == "ASC")
{
switch (ViewState["SortField"] as string)
{
case "LKey":
this.SortedDetails = this.Details.OrderBy(d => d.LKey);
break;
case "MName":
this.SortedDetails = this.Details.OrderBy(d => d.MaterialName);
break;
case "FMSQOH":
this.SortedDetails = this.Details.OrderBy(d => d.FMSQOH);
break;
case "CCQOH":
this.SortedDetails = this.Details.OrderBy(d => d.CCQOH);
break;
case "FMSQOHVary":
this.SortedDetails = this.Details.OrderBy(d => d.FMSQOHVary);
break;
default:
this.SortedDetails = this.Details.OrderBy(d => d.LKey);
break;
}
}
else
{
switch (ViewState["SortField"] as string)
{
case "LKey":
this.SortedDetails = this.Details.OrderByDescending(d => d.LKey);
break;
case "MName":
this.SortedDetails = this.Details.OrderByDescending(d => d.MaterialName);
break;
case "FMSQOH":
this.SortedDetails = this.Details.OrderByDescending(d => d.FMSQOH);
break;
case "CCQOH":
this.SortedDetails = this.Details.OrderByDescending(d => d.CCQOH);
break;
case "FMSQOHVary":
this.SortedDetails = this.Details.OrderByDescending(d => d.FMSQOHVary);
break;
default:
this.SortedDetails = this.Details.OrderByDescending(d => d.LKey);
break;
}
}
太可怕了。我担心的是,我会为每个新的排序字段添加2*n个case语句。请问正确的路是什么?
我已经经历过了。。我最后发现了一个通用的解决方案,它使用反射对IEnumerable对象进行排序。
http://zhousanfeng.wordpress.com/2009/12/01/a-generic-comparersorter-class%E8%BD%AC/
这将是你如何使用它
Sorter<TestClass> sort = new Sorter<TestClass>(this.Deatils, "LKey ASC");
List<TestClass> sorted = sort.GetSortedList();
谨致问候。
在执行排序(未测试)之前,将Func
分配给orderby方法:
public IOrderedEnumerable<TSource> OrderFunc<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector
);
OrderFunc order;
if ((ViewState["SortDirection"] as string) == "ASC")
order = Enumerable.OrderBy;
else
order = Enumerable.OrderByDescending;
switch (ViewState["SortField"] as string)
{
case "LKey":
this.SortedDetails = order(this.Details, d => d.LKey);
break;
case "MName":
this.SortedDetails = order(this.Details, d => d.MaterialName);
break;
case "FMSQOH":
this.SortedDetails = order(this.Details, d => d.FMSQOH);
break;
case "CCQOH":
this.SortedDetails = order(this.Details, d => d.CCQOH);
break;
case "FMSQOHVary":
this.SortedDetails = order(this.Details, d => d.FMSQOHVary);
break;
default:
this.SortedDetails = order(this.Details, d => dLKey);
break;
}