如何使用DataTable中的Linq查找重复记录
问题描述:
如果我的DataTable
Here is if my DataTable
DataTable dt = new DataTable();
dt.Rows.Add(2,Test1,Sample1);
dt.Rows.Add(2,Test2,Sample2);
dt.Rows.Add(4,Test3,Sample3);
dt.Rows.Add(4,Test4,Sample4);
dt.Rows.Add(2,Test5,Sample5);
我想显示消息第4类存在重复记录
它可以使用两个循环比较,但我想要一个优化的代码,将返回我的重复记录,我会显示一条消息。代码可能是使用Linq,如果任何身体知道请分享..?
I want to display message Duplicate record exist for class 4 it is possbile by using two loops by comparing, but i want an optimized code that will return me the duplicate record and i will display a message. The code may be using Linq if any body know please share..?
答
假设你得到一个重复的记录,当值的第一列对于两行或更多行是相同的:
Assuming that you get a duplicate record when the value of the first column is identical for two or more rows:
var duplicates = dt.AsEnumerable().GroupBy(r => r[0]).Where(gr => gr.Count() > 1);
这是一个例子:
DataTable dt = new DataTable();
dt.Columns.Add();
dt.Columns.Add();
dt.Columns.Add();
dt.Rows.Add(1, "Test1", "Sample1");
dt.Rows.Add(2, "Test2", "Sample2");
dt.Rows.Add(3, "Test3", "Sample3");
dt.Rows.Add(4, "Test4", "Sample4");
dt.Rows.Add(5, "Test5", "Sample5");
var duplicates = dt.AsEnumerable().GroupBy(r => r[0]).Where(gr => gr.Count() > 1).ToList();
Console.WriteLine("Duplicate found: {0}", duplicates.Any());
dt.Rows.Add(1, "Test6", "Sample6"); // Duplicate on 1
dt.Rows.Add(1, "Test6", "Sample6"); // Duplicate on 1
dt.Rows.Add(3, "Test6", "Sample6"); // Duplicate on 3
dt.Rows.Add(5, "Test6", "Sample6"); // Duplicate on 5
duplicates = dt.AsEnumerable().GroupBy(r => r[0]).Where(gr => gr.Count() > 1).ToList();
if (duplicates.Any())
Console.WriteLine("Duplicate found for Classes: {0}", String.Join(", ", duplicates.Select(dupl => dupl.Key)));
Console.ReadLine();