小编典典

检查dataTable中是否存在值?

c#

我有带有两列 AuthorBookname的 DataTable 。

我想检查给定的字符串值 Author是否 已存在于DataTable中。是否有一些内置方法可以检查它,例如Arrays
array.contains


阅读 416

收藏
2020-05-19

共1个答案

小编典典

你可以用LINQ-to-DataSetEnumerable.Any

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

另一种方法是使用DataTable.Select

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

问:如果我们不知道标题列,又想查找行PEPSIc列中是否存在任何单元格值,该怎么办?我可以循环查找所有内容,但是有更好的方法吗?–

是的,您可以使用以下查询:

DataColumn[] columns = tbl.Columns.Cast<DataColumn>().ToArray();
bool anyFieldContainsPepsi = tbl.AsEnumerable()
    .Any(row => columns.Any(col => row[col].ToString() == "PEPSI"));
2020-05-19