C# - 从数据表中删除具有相同列值的行 [英] C# - Remove rows with the same column value from a DataTable

查看:22
本文介绍了C# - 从数据表中删除具有相同列值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 DataTable 看起来像这样:

I have a DataTable which looks like this:

 ID   Name    DateBirth
.......................
 1     aa      1.1.11
 2     bb      2.3.11
 2     cc      1.2.12
 3     cd      2.3.12

删除具有相同 ID 的行的最快方法是得到这样的结果(保留第一次出现,删除下一​​次):

Which is the fastest way to remove the rows with the same ID, to get something like this (keep the first occurrence, delete the next ones):

 ID   Name    DateBirth
.......................
 1     aa      1.1.11
 2     bb      2.3.11
 3     cd      2.3.12

我不想重复传递表格行,因为行号很大.如果可能,我想使用一些 LinQ,但我想这将是一个很大的查询,我必须使用比较器.

I don't want to double pass the table rows, because the row number is big. I want to use some LinQ if possible, but I guess it will be a big query and I have to use a comparer.

推荐答案

你可以使用LINQ to DataTable,根据列ID来区分,你可以group by此列,然后先选择:

You can use LINQ to DataTable, to distinct based on column ID, you can group by on this column, then do select first:

  var result = dt.AsEnumerable()
                 .GroupBy(r => r.Field<int>("ID"))
                 .Select(g => g.First())
                 .CopyToDataTable();

这篇关于C# - 从数据表中删除具有相同列值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆