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. 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 开发者_JAVA技巧the method didnt seem to exist. Please advise
P.S : Am using c# in vs 2010
DataTable is not default uses 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
getting understanding your to use Field<T>
You cannot use the method because DataRowCollection
doesn't implement IEnumerable<T>
. You need to use the AsEnumerable()
extension:
var dataRowQuery= myDataTable.AsEnumerable().Where(row => ...
You might also need a project reference to System.Data.DataSetExtensions
for this to work.
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. 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.
精彩评论