Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if row exists in DataTable?

I have a datatable and a row. I want to import the row to the datatable only if it does not exist in the datatable.

How can i do that?

like image 829
Curious Avatar asked Sep 28 '14 18:09

Curious


2 Answers

If you use a typed DataSet, I.e. declared in design time, the "linq Contains method" takes a typed DataRow. The default IEqualityComparer will compare all values in the DataRow. (Which is normally useless, since you should have a key defined).

DataSet1 ds = new DataSet1();
DataSet1.DataTable1Row row = ds.DataTable1.AddDataTable1Row(bla, bla);
bool exists = ds.DataTable1.Contains(row);
like image 169
S22 Avatar answered Oct 18 '22 17:10

S22


You can use LINQ to check if row is present in datatable. Follow this solution, and replace "id" with your row's primary key, by which you can uniquely identify a row in a table.

DataRow dr = null; // assign your DR here
DataTable dt = new DataTable(); // assign Datatable instance here.
var k = (from r in dt.Rows.OfType<DataRow>()  where r["id"].ToString() == dr["id"].ToString() select r).FirstOrDefault();
if(k != null)
{  // Row is present }
like image 42
Arindam Nayak Avatar answered Oct 18 '22 17:10

Arindam Nayak