检查数据表中是否存在值? [英] Check if value exists in dataTable?

查看:24
本文介绍了检查数据表中是否存在值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有包含两列 AuthorBookname 的 DataTable.

我想检查给定的字符串值 Author 是否已经存在于 DataTable 中.是否有一些内置的方法来检查它,比如数组array.contains?

解决方案

您可以使用 LINQ-to-DataSetEnumerable.Any:

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

另一种方法是使用 DataTable.Select:

DataRow[] foundAuthors = tbl.Select("Author = '" + searchAuthor + "'");if(foundAuthors.Length != 0){//做一点事...}

<小时><块引用>

问:如果我们不知道列标题,我们想找到是否有怎么办单元格值 PEPSI 存在于任何行的 c 列中吗?我可以把它全部循环到找出但有更好的方法吗?——

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

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

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?

解决方案

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"));

这篇关于检查数据表中是否存在值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆