检查DataTable中存在的价值? [英] Check if value exists in dataTable?
问题描述
我有两列数据表作者,BOOKNAME。
我要检查,如果给定的字符串值,笔者在数据表中已经存在。有一些内置的方法来检查它,像阵列array.contains?
您可以使用 LINQ到数据集
与 Enumerable.Any
:
字符串笔者=约翰格里沙姆
布尔包含= tbl.AsEnumerable()任何(行=>作者== row.Field<串GT;(作者))。
另一种方法是使用 DataTable.Select
:
的DataRow [] = foundAuthors tbl.Select(作者='+ searchAuthor +');
如果(foundAuthors.Length!= 0)
{
// 做一点事...
}
问:如果我们不知道的列标题,我们希望以查找是否存在
单元格的值PEPSI
中的任何rows'c列是否存在?我可以全部循环
找出,但有没有更好的办法? -
块引用>是的,你可以使用这个查询:
的DataColumn [] =列与tbl.Columns.Cast LT; DataColumn的方式>()ToArray的();
布尔anyFieldContainsPepsi = tbl.AsEnumerable()
。任何(行=> columns.Any(COL =>行[COL]的ToString()==百事));I have DataTable with two columns Author, Bookname.
I want to check if given string value Author already exists in DataTable. Is there some built in method to check it, like for Arrays array.contains ?
解决方案You can use
LINQ-to-DataSet
withEnumerable.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"));
这篇关于检查DataTable中存在的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!