C# 检查数据表中是否存在值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10703320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:54:10  来源:igfitidea点击:

Check if value exists in dataTable?

c#datatable

提问by valterriann

I have DataTable with two columns Authorand Bookname.

我有两列AuthorBookname 的DataTable 。

I want to check if the given string value Authoralready exists in the DataTable. Is there some built in method to check it, like for Arrays array.contains?

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

采纳答案by Tim Schmelter

You can use LINQ-to-DataSetwith Enumerable.Any:

你可以用LINQ-to-DataSetEnumerable.Any

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

Another approach is to use DataTable.Select:

另一种方法是使用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 PEPSIexist in any rows'c columns? I can loop it all to find out but is there a better way? –

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

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

回答by mservidio

You can use Linq. Something like:

您可以使用 Linq。就像是:

bool exists = dt.AsEnumerable().Where(c => c.Field<string>("Author").Equals("your lookup value")).Count() > 0;

回答by Blast_dan

you could set the database as IEnumberable and use linq to check if the values exist. check out this link

您可以将数据库设置为 IEnumberable 并使用 linq 检查值是否存在。看看这个链接

LINQ Query on Datatable to check if record exists

数据表上的 LINQ 查询以检查记录是否存在

the example given is

给出的例子是

var dataRowQuery= myDataTable.AsEnumerable().Where(row => ...

you could supplement where with any

你可以用任何来补充 where

回答by Antonio Bakula

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

add to your using clause :

添加到您的 using 子句:

using System.Linq;

and add :

并添加:

System.Data.DataSetExtensions

System.Data.DataSetExtensions

to references.

到参考。

回答by Kibbee

You should be able to use the DataTable.Select()method. You can us it like this.

您应该能够使用DataTable.Select()方法。你可以这样我们。

if(myDataTable.Select("Author = '" + AuthorName.Replace("'","''") + '").Length > 0)
    ...

The Select() funciton returns an array of DataRows for the results matching the where statement.

Select() 函数为与 where 语句匹配的结果返回一个 DataRow 数组。