4

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 the method didnt seem to exist. Please advise

P.S : Am using c# in vs 2010

paradox
  • 1,248
  • 5
  • 20
  • 32
  • You can use [FirstOrDefault](http://msdn.microsoft.com/en-us/library/bb340482.aspx) to check if record exists. – Renatas M. May 23 '11 at 06:37

3 Answers3

5

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>

anishMarokey
  • 11,279
  • 2
  • 34
  • 47
3

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!

Edwin de Koning
  • 14,209
  • 7
  • 56
  • 74
0

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.

Alex R.
  • 4,664
  • 4
  • 30
  • 40