Check if row exists in DataTable?

I have a date and a string. I want to import a string into datatable only if it does not exist in datatable.

How can i do this?

+6
source share
6 answers

If you are using a typed dataset declared during development, the linq Contains method accepts a typed DataRow. By default, IEqualityComparer will compare all values ​​in a DataRow. (Which is usually useless, since you must have a specific key).

DataSet1 ds = new DataSet1(); DataSet1.DataTable1Row row = ds.DataTable1.AddDataTable1Row(bla, bla); bool exists = ds.DataTable1.Contains(row); 
+10
source

if you want to check all cells in a DataRow , you can try this function:

 bool ContainDataRowInDataTable(DataTable T,DataRow R) { foreach (DataRow item in T.Rows) { if (Enumerable.SequenceEqual(item.ItemArray, R.ItemArray)) return true; } return false; } 
+7
source

You can use LINQ to check for the presence of a string in a datatable. Follow this solution and replace "id" with the primary key of the row, with which you can uniquely identify the row in the 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 } 
+6
source

you can use Contains as below

 if(DataTable.Columns.Contains("RowName")) { //Do some stuffs here } 
+3
source
 if ( Datatable1.Rows[NumOfRow].ToString().Deleted == "Deleted") 
0
source

You should check for the existence of strings by comparing the primary keys:

 static bool RowExists(DataTable table, DataRow row) { var pk = table.PrimaryKey .Select(column => row[column, DataRowVersion.Original]) .ToArray(); return table.Rows.Contains(pk); } 
0
source

Source: https://habr.com/ru/post/975973/


All Articles