问题描述
我接到了一个数据集正在建设的报告。该数据集使用排序属性来对数据进行排序。我知道我可以创建一个排序的前pression是这样的:
I've got a report being built from a dataset. The dataset uses the Sort property to order the data. I know that I can create a sort expression like this:
场递减,Field2的ASC
"field desc, field2 asc"
但我现在需要的是一种方法可以做到自定义排序。在SQL中,我可以做这样的事情进行自定义排序:
But what I need now is a way to do a custom sort. In SQL, I can perform a custom sort by doing something like this:
order by
case when field = 'Some Value' then 0 end
case when field = 'Another Value' then 1 end
要基本上重新定义我的排序(即,一些价值来之前另一种价值)。
To basically re-define my sort (i.e, Some Value comes before Another Value).
是否有可能做作为对一个DataView?
Is it possible to do something similar as a sort expression against a DataView?
推荐答案
好吧,我刚刚刮起这件事真正的快,并没有完成所有的neccessary错误处理和空检查,但它应该给你一个想法和应足以让你开始:
Ok, I just whipped this up real quick, and didn't do all the neccessary error handling and null checking, but it should give you an idea and should be enough to get you started:
public static class DataTableExtensions
{
public static DataView ApplySort(this DataTable table, Comparison<DataRow> comparison)
{
DataTable clone = table.Clone();
List<DataRow> rows = new List<DataRow>();
foreach (DataRow row in table.Rows)
{
rows.Add(row);
}
rows.Sort(comparison);
foreach (DataRow row in rows)
{
clone.Rows.Add(row.ItemArray);
}
return clone.DefaultView;
}
}
用法:
DataTable table = new DataTable();
table.Columns.Add("IntValue", typeof(int));
table.Columns.Add("StringValue");
table.Rows.Add(11, "Eleven");
table.Rows.Add(14, "Fourteen");
table.Rows.Add(10, "Ten");
table.Rows.Add(12, "Twelve");
table.Rows.Add(13, "Thirteen");
//排序的StringValue:
//Sort by StringValue:
DataView sorted = table.ApplySort((r, r2) =>
{
return ((string)r["StringValue"]).CompareTo(((string)r2["StringValue"]));
});
结果:
11十一
14十四
10十大
13十三
12十二
//排序INTVALUE:
//Sort by IntValue:
DataView sorted = table.ApplySort((r, r2) =>
{
return ((int)r["IntValue"]).CompareTo(((int)r2["IntValue"]));
});
结果:
10十大
11十一
13十三
12十二
14十四
编辑:改成了扩展方法
现在在你的LAMBDA,(或者你可以创建一个完全成熟的比较法),你可以做任何类型的自定义排序逻辑,你所需要的。记住,-1是小于,0等于,和1大于
Now in your Lambda, (or you can create a full blown Comparison method) you can do any kind of custom sorting logic that you need. Remember, -1 is less than, 0 is equal to, and 1 is greater than.
这篇关于DataView.Sort - 不仅仅是递增/递减(需要自定义排序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!