[英]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
列替换为TagId
和TagName
列吗? 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.