按名称列中的姓氏过滤数据表 [英] Filter datatable by lastname in name column
问题描述
我有一个数据表,如
名称ID
Kingshuk Dutta 2
Tapas Nayak 4
Prakash Kiran 7
我要按名称列对数据表进行排序,但仅使用最后一个名称。
它应该显示如下:
名称ID
Kingshuk Dutta 2
Prakash Kiran 7
Tapas Nayak 4
我尝试过:
数据表是这样的,我要对它进行排序。
我想把字符串数组中的名字取出来然后排序,然后插入数据表。但这是错误的想法。请建议。
如果将名字和姓氏拆分为单独的列,它将使您的数据处理变得更加容易。
解决方案1提供了最简单的方法。但是,如果你真的需要一个Name字段,有一种方法可以对它进行排序:
dt.AsEnumerable()。OrderBy(x = > (x.ItemArray [ 0 ] as string )。拆分(' ') [ 1 ])。CopyToDataTable(); // 其中'dt'是您的DataTable
AsEnumerable
返回EnumerableRowCollection< DataRow>
,您可以在其上调用OrderBy
有一个lambda表达式,告诉你使用名字的第二个单词。这将返回OrderedEnumerableRowCollection< DataRow>
,您可以调用CopyToDataTable
将此集合转换为新的数据表
I have a Datatable like
Name ID Kingshuk Dutta 2 Tapas Nayak 4 Prakash Kiran 7
I've to sort the datatable by Name column but using the LAST NAME only.
It should show like:
Name ID Kingshuk Dutta 2 Prakash Kiran 7 Tapas Nayak 4
What I have tried:
The datatable is coming like this, I've to sort it.
I thought of taking the names in a string array and then sort, afterwards insert into datatable. but thats wrong idea. Please suggest.
If you split the First name and Last name into separate columns it will make working with your data a lot easier.
Solution 1 provides the simplest way to do this. If, however, you really need to have a single Name field, there is a way to sort it:
dt.AsEnumerable().OrderBy(x => (x.ItemArray[0] as string).Split(' ')[1]).CopyToDataTable(); // where 'dt' is your DataTable
AsEnumerable
returns anEnumerableRowCollection<DataRow>
, on which you can callOrderBy
with a lambda expression that tells to use the second word of the name. This returns anOrderedEnumerableRowCollection<DataRow>
and you can callCopyToDataTable
to convert this collection into a newDataTable
.
这篇关于按名称列中的姓氏过滤数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!