获取具有C#中不同行的数据表 [英] get the datatable with distinct rows in C#
本文介绍了获取具有C#中不同行的数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于从电子表格中获取了数据,因此我返回了一个数据表.我只需要显示结果集,而不同的行仅取决于一列.
I have a datatable returned as a result of fetching data from a spreadsheet. I need to display the resultset only with the distinct rows depends up on only a column.
例如,我有一个带有列的数据表
For example I have a datatable with columns
id | name | age | email
然后,如果列出了多个具有相同 id 的记录,则应将其省略.我尝试过
Then if more than one record with the same id is listed it should omitted. I tried
dt = dt.DefaultView.ToTable(true)
,但它返回所有列的不同记录.我只需要基于ID的不同记录即可.
but it returns the distinct records with respect to all columns. I need the distinct records only based on the id.
有人可以帮我吗?
推荐答案
您可以使用GroupBy
:-
DataTable result = dt.AsEnumerable()
.GroupBy(x => x.Field<int>("Id"))
.Select(x => x.First()).CopyToDataTable();
请注意,如果匹配Id
,我将获取第一条记录,而忽略其余部分.
Please note, in case of a matching Id
, I am taking the first record and ignoring the rest.
这篇关于获取具有C#中不同行的数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文