Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value exists in dataTable?

Tags:

c#

datatable

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?

like image 776
valterriann Avatar asked May 22 '12 13:05

valterriann


People also ask

How do you check if a column contains a value in DataTable?

DataTable.Rows(0)(“columnname”).ToString = "" You can check it by the following single sentence.

How to check value present in DataTable in c#?

Another approach is to use DataTable. Select : DataRow[] foundAuthors = tbl. Select("Author = '" + searchAuthor + "'"); if(foundAuthors.

How to check if value exists in DataTable uipath?

Hi @Ravi, to check whether a string is present in a data table or not, you need to use ReadRange activity to read your excel file and store its output in a data table. Then use ForEachRow activity to read each row of the data table and use If activity to put the condition for matching the string.

How do you check if a row exists in a DataTable C#?

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.


3 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 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"));
like image 70
Tim Schmelter Avatar answered Oct 16 '22 10:10

Tim Schmelter


You can use Linq. Something like:

bool exists = dt.AsEnumerable().Where(c => c.Field<string>("Author").Equals("your lookup value")).Count() > 0;
like image 43
mservidio Avatar answered Oct 16 '22 09:10

mservidio


DataRow rw = table.AsEnumerable().FirstOrDefault(tt => tt.Field<string>("Author") == "Name");
if (rw != null)
{
// row exists
}

add to your using clause :

using System.Linq;

and add :

System.Data.DataSetExtensions

to references.

like image 11
Antonio Bakula Avatar answered Oct 16 '22 11:10

Antonio Bakula