[英]Sorting datatable by two columns with one column asc and the other one desc c#
I have multiple columns in datatable like this: 我在数据表中有多个列,如下所示:
COL1 COL2 COL3
aaa 5 bla
bbb 8 blablabla
ccc 11 blabla
ddd 9 bl
eee 6 blabl
I'm trying to sort this datatable by COL1 asc and by COL2 desc BOTH! 我正在尝试按COL1 asc和COL2 desc排序此数据表!
I have tried the following solution but it doesn't exactly sort the second column: 我尝试了以下解决方案,但未对第二列进行完全排序:
DataTable dt = GetMyData();
dt.DefaultView.Sort = "COL1";
dt.DefaultView.Sort = "COL2 DESC";
dt = dt.DefaultView.ToTable();
Use LINQ to DataSet/DataTable 使用LINQ来DataSet / DataTable
https://msdn.microsoft.com/en-us/library/bb386977.aspx https://msdn.microsoft.com/zh-CN/library/bb386977.aspx
var newDt = dt.AsEnumerable()
.OrderByDescending(x => x.Field<int>("COL2"))
.ThenBy(x => x.Field<string>("COL1"))
.CopyToDataTable();
DataView sortedView = new DataView(dt);
// Sort by COL1 and COL2
sortedView.Sort = "COL1 DESC, COL2 ASC";
after this you should have sorted records in the data view 之后,您应该已经在数据视图中对记录进行了排序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.