[英]Check if value exists in dataTable?
I have DataTable with two columns Author and Bookname . 我有DataTable,有两列Author和Bookname 。
I want to check if the given string value Author already exists in the DataTable. 我想检查给定的字符串值Author是否已存在于DataTable中。 Is there some built in method to check it, like for Arrays
array.contains
? 是否有一些内置的方法来检查它,比如Arrays
array.contains
?
You can use LINQ-to-DataSet
with Enumerable.Any
: 您可以在
Enumerable.Any
使用LINQ-to-DataSet
:
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
PEPSI
exist in any rows'c columns?问:如果我们不知道列标题,我们想要查找任何行的列中是否存在任何单元格值
PEPSI
,该怎么办? 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"));
You can use Linq. 你可以使用Linq。 Something like:
就像是:
bool exists = dt.AsEnumerable().Where(c => c.Field<string>("Author").Equals("your lookup value")).Count() > 0;
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. 参考。
You should be able to use the DataTable.Select() method. 您应该能够使用DataTable.Select()方法。 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. Select()函数返回一个DataRows数组,用于匹配where语句的结果。
you could set the database as IEnumberable and use linq to check if the values exist. 您可以将数据库设置为IEnumberable并使用linq检查值是否存在。 check out this link
看看这个链接
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 你可以补充任何地方
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.