Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find duplicate record using Linq from DataTable

Tags:

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);

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..?

like image 431
Khalid Rafique Avatar asked Jan 20 '12 09:01

Khalid Rafique


People also ask

How to find duplicate values in DataTable in asp net?

Below is the right way of finding the duplicate records and save them into new datatable. RowId = c. Field< string >( "RowId" ), //column names for checking duplicate values.


1 Answers

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);

Here is an example:

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();
like image 176
Seb Boulet Avatar answered Jan 23 '23 12:01

Seb Boulet