[英]Remove Duplicates from Datatable with LINQ without keeping a duplicated entry at all
I have a Datatable
with several Columns which I want to remove all duplicates from like that我有一个包含多个列的Datatable
,我想从中删除所有重复项
Dt1 = Dt1 .AsEnumerable().GroupBy(r => new { filename = r.Field<string>("filename1"), filesize = r.Field<string>("filesizeinkb") }).Select(g => g.First()).CopyToDataTable();
However above code leaves one entry (the first one that is found) in the DataTable via the Select.First
at the end of the LINQ code.但是,上面的代码通过 LINQ 代码末尾的Select.First
在 DataTable 中留下一个条目(找到的第一个条目)。
Is there a way to remove all duplicates and keep none?有没有办法删除所有重复项并且不保留?
Edit: Example what the code is doing now and what it should do.编辑:示例代码现在正在做什么以及应该做什么。
Datatable with entries like that具有类似条目的数据表
Name姓名 | Filesize文件大小 | Filename文件名 |
---|---|---|
One一 | 50 50 | Fileone文件一 |
Two二 | 50 50 | Fileone文件一 |
Three三 | 50 50 | Filetwo文件二 |
Four四 | 50 50 | Filethree文件三 |
Above LINQ will now remove Line 2 as Filename and Filesize are the same.上面的 LINQ 现在将删除第 2 行,因为 Filename 和 Filesize 相同。 However Line 1 will stay as the LINQ Code selects the first duplicated entry.但是,当 LINQ 代码选择第一个重复条目时,第 1 行将保留。
I want to have removed line 1 and line 2 from the Datatable.我想从数据表中删除第 1 行和第 2 行。
Dt1 = Dt1.AsEnumerable()
.GroupBy(r => new { filename = r.Field<string>("filename1"), filesize = r.Field<string>("filesizeinkb") })
.Where(g => g.Count() == 1)
.Select(g => g.First())
.CopyToDataTable();
That will discard any groups with more than one item, then get the first (and only) item from the rest.这将丢弃任何包含多个项目的组,然后从其余项目中获取第一个(也是唯一一个)项目。
Note: This was blindly typed here, so there might be some typos in the code.注意:这里是盲目输入的,所以代码中可能有一些拼写错误。
Idea is, get the number of rows inside your DataTable
, and go trough each of them, and do what you already did.想法是,获取DataTable
中的行数,然后遍历它们中的每一个,然后做你已经做过的事情。
int NumOfItems = Dt1.AsEnumarable().ToList();
for(int i = 0; i < NumOfItems.Count; i++)
{
Dt1 = Dt1 .AsEnumerable().GroupBy(r => new { filename = r.Field<string>("filename1"), filesize = r.Field<string>("filesizeinkb") }).Select(g => g.First()).CopyToDataTable();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.