简体   繁体   English

如何对部分列值应用数据表排序

[英]How can apply Datatable sorting on a part of column value

I have a DataTable . 我有一个DataTable and i want to apply sorting on a column using C# Sort function. 我想使用C# Sort功能对列进行Sort but I have multiple value into column(with separator - Æ). 但是我在列中有多个值(带分隔符-Æ)。

So i really want to apply sorting on a specific part of a column. 所以我真的很想对列的特定部分应用排序。 It is possible or not. 是否可能。

For Example - My DataTable column is Tag . 例如-我的DataTable列是Tag Column Tag have two value - TagId + TagName Tag具有两个值TagId + TagName
Now i want to apply sort only on TagName . 现在我只想对TagName进行排序。

How can i do ? 我能怎么做 ?

Example - My DataTable dt 示例-我的DataTable dt

Tag 标签

10ÆAA -------->( TagId Æ TagName ) 10ÆAA-------->( TagId Æ TagName

15ÆBB -------->( TagId Æ TagName ) 15ÆBB-------->( TagId Æ TagName

0ÆCC -------->( TagId Æ TagName ) 0ÆCC-------->( TagId Æ TagName

20ÆGG -------->( TagId Æ TagName ) 20ÆGG-------->( TagId Æ TagName

In code - 在代码中-

dt.DefaultView.Sort = "Tag DESC"; // -- I try this this code but it apply sorting on whole column //-我尝试使用此代码,但对整个列进行排序

I want result like this (sorted according TagName ) 我想要这样的结果(根据TagName排序)

Tag 标签

20ÆGG 20ÆGG

0ÆCC 0ÆCC

15ÆBB 15ÆBB

10ÆAA 10ÆAA

Not like this (not sorted according TagId ) 不是这样(未根据TagId排序)

Tag 标签

0ÆCC 0ÆCC

10ÆAA 10ÆAA

15ÆBB 15ÆBB

20ÆGG 20ÆGG

Can you replace the Tag column with TagId and TagName columns? 可以将Tag列替换为TagIdTagName列吗? That would make your data structure make sense, and in turn make working with it (eg sorting) make sense. 这将使您的数据结构有意义,进而使使用它(例如排序)变得有意义。 If not, I think this ought to work: 如果没有,我认为这应该起作用:

var ordered = dt.AsEnumerable().OrderByDescending(
 x => x.Field<string>("Tag").Substring(x.Field<string>("Tag").IndexOf("Æ") + 1));

If you have original columns in your datatable then you can use those columns for sorting. 如果你在有原始列datatable ,那么你可以使用这些列进行排序。
Else you will have to loop through data-table each row and create a new data-table and use it for your code. 否则,您将不得不遍历data-table每一行,并创建一个新的data-table并将其用于代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM