[英]LINQ Query on Datatable to check if record exists
I want to perform a LINQ query on a datatable called Records and check if a record exists. 我想对名为Records的数据表执行LINQ查询,并检查是否存在记录。 If it exists, I want to find out the row which it is in. How might I go about doing this?
如果它存在,我想找出它所在的行。我怎么能这样做呢?
I wanted to do a .where on my datatable after adding the system.linq namespace but the method didnt seem to exist. 我想在添加system.linq命名空间后在我的数据表上做一个.where但该方法似乎不存在。 Please advise
请指教
PS : Am using c# in vs 2010 PS:我在2010年使用c#
DataTable is not default uses Enumerable. DataTable不是默认使用Enumerable。 you have to convert to
你必须转换为
var result = from p in dataTable.AsEnumerable()
where p.Field("ID") == 2
select p.Field("Name");
if(result.Any())
{
//do your work
}
read this article for 阅读这篇文章
http://blogs.msdn.com/b/adonet/archive/2007/01/26/querying-datasets-introduction-to-linq-to-dataset.aspx http://blogs.msdn.com/b/adonet/archive/2007/01/26/querying-datasets-introduction-to-linq-to-dataset.aspx
getting understanding your to use Field<T>
了解你使用
Field<T>
You cannot use the method because DataRowCollection
doesn't implement IEnumerable<T>
. 您无法使用该方法,因为
DataRowCollection
未实现IEnumerable<T>
。 You need to use the AsEnumerable()
extension: 您需要使用
AsEnumerable()
扩展:
var dataRowQuery= myDataTable.AsEnumerable().Where(row => ...
You might also need a project reference to System.Data.DataSetExtensions
for this to work. 您可能还需要一个对
System.Data.DataSetExtensions
的项目引用,以使其工作。
Good luck! 祝好运!
If you have a table such as: 如果你有一个表,如:
DataTable dt = new DataTable();
dt.Columns.Add("rownum", typeof(Int32));
dt.Columns.Add("val", typeof(String));
dt.Rows.Add(1, "a");
dt.Rows.Add(2, "b");
dt.Rows.Add(3, "c");
Then, 然后,
Console.WriteLine(
dt.Rows.IndexOf(dt.AsEnumerable().Where(c => c.Field<String>(1) == "d").FirstOrDefault())); // `1:= index of column
would result -1
because "d"
is not found. 会导致
-1
因为找不到"d"
。 But, 但,
Console.WriteLine(
dt.Rows.IndexOf(dt.AsEnumerable().Where(c => c.Field<String>(1) == "b").FirstOrDefault())); // `1:= index of column
would result 1
, representing the row where "b"
is in. 将得到
1
,表示"b"
所在的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.