Check if value exists in dataTable?

valterriann picture valterriann · May 22, 2012 · Viewed 242.1k times · Source

I have DataTable with two columns Author and Bookname.

I want to check if the given string value Author already exists in the DataTable. Is there some built in method to check it, like for Arrays array.contains?

Answer

Tim Schmelter picture Tim Schmelter · May 22, 2012

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 do not know the columns Headers and we want to find if any cell value PEPSI exist in any rows'c columns? I can loop it all to 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"));