Check if value exists in dataTable?

I have a DataTable with two columns Author and Bookname.

I want to check if the given value of the Author row already exists in the DataTable. Is there a built-in method for checking, for example, for arrays array.contains ?

+56
c # datatable
May 22 '12 at 13:44
source share
5 answers

You can use LINQ-to-DataSet with Enumerable.Any :

 String author = "John Grisham"; bool contains = tbl.AsEnumerable().Any(row => author == row.Field<String>("Author")); 

Another approach is to use DataTable.Select :

 DataRow[] foundAuthors = tbl.Select("Author = '" + searchAuthor + "'"); if(foundAuthors.Length != 0) { // do something... } 



Q: what if we don't know the Header columns, and we want to find if they PEPSI cell value exists in the columns of any rows? I can find out, but is there a better way? -

Yes, you can use this query:

 DataColumn[] columns = tbl.Columns.Cast<DataColumn>().ToArray(); bool anyFieldContainsPepsi = tbl.AsEnumerable() .Any(row => columns.Any(col => row[col].ToString() == "PEPSI")); 
+155
May 22 '12 at 1:46 pm
source share
β€” -

You can use Linq. Something like:

 bool exists = dt.AsEnumerable().Where(c => c.Field<string>("Author").Equals("your lookup value")).Count() > 0; 
+7
May 22 '12 at
source share
 DataRow rw = table.AsEnumerable().FirstOrDefault(tt => tt.Field<string>("Author") == "Name"); if (rw != null) { // row exists } 

add to your sentence:

 using System.Linq; 

and add:

System.Data.DataSetExtensions

to the links.

+6
May 22 '12 at
source share

You can use the DataTable.Select () method. You can do this to us.

 if(myDataTable.Select("Author = '" + AuthorName.Replace("'","''") + '").Length > 0) ... 

The Select () function returns an array of DataRows for results matching the where query.

+4
May 22 '12 at 13:52
source share

you can set the database as IEnumberable and use linq to check if values ​​exist. check this link

LINQ query in Datatable to check if a record exists

given example

 var dataRowQuery= myDataTable.AsEnumerable().Where(row => ... 

you can complement where with

0
May 22 '12 at
source share



All Articles