Check if value exists in dataTable?
C#DatatableC# Problem Overview
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
?
C# Solutions
Solution 1 - C#
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"));
Solution 2 - C#
You can use Linq. Something like:
bool exists = dt.AsEnumerable().Where(c => c.Field<string>("Author").Equals("your lookup value")).Count() > 0;
Solution 3 - C#
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.
Solution 4 - C#
You should be able to use the http://msdn.microsoft.com/en-us/library/det4aw50.aspx">DataTable.Select()</a> method. You can us it like this.
if(myDataTable.Select("Author = '" + AuthorName.Replace("'","''") + '").Length > 0)
...
The Select() funciton returns an array of DataRows for the results matching the where statement.
Solution 5 - C#
you could set the database as IEnumberable and use linq to check if the values exist. check out this link
https://stackoverflow.com/questions/6093560/linq-query-on-datatable-to-check-if-record-exists
the example given is
var dataRowQuery= myDataTable.AsEnumerable().Where(row => ...
you could supplement where with any