<p>I'm trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example:</p>

<pre><code>var results = from myRow in myDataTable
where results.Field("RowNo") == 1
select results;
</code></pre>

<p>This is not allowed. How do I get something like this working?</p>

<p>I'm amazed that LINQ queries are not allowed on DataTables!</p>

[{'answer_id': 10856, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 6, 'selected': False, 'text': "<p>It's not that they were deliberately not allowed on DataTables, it's just that DataTables pre-date the IQueryable and generic IEnumerable constructs on which Linq queries can be performed. </p>\n\n<p>Both interfaces require some sort type-safety validation. DataTables are not strongly typed. This is the same reason why people can't query against an ArrayList, for example.</p>\n\n<p>For Linq to work you need to map your results against type-safe objects and query against that instead.</p>\n"}, {'answer_id': 10857, 'author': 'David Wengier', 'author_id': 489, 'author_profile': 'https://Stackoverflow.com/users/489', 'pm_score': 4, 'selected': False, 'text': '<p>You can use LINQ to objects on the Rows collection, like so:</p>\n\n<pre><code>var results = from myRow in myDataTable.Rows where myRow.Field("RowNo") == 1 select myRow;\n</code></pre>\n'}, {'answer_id': 10893, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 6, 'selected': False, 'text': '<p>As @ch00k said:</p>\n\n<pre><code>using System.Data; //needed for the extension methods to work\n\n...\n\nvar results = \n    from myRow in myDataTable.Rows \n    where myRow.Field&lt;int&gt;("RowNo") == 1 \n    select myRow; //select the thing you want, not the collection\n</code></pre>\n\n<p>You also need to add a project reference to <code>System.Data.DataSetExtensions</code></p>\n'}, {'answer_id': 11593, 'author': 'Collin K', 'author_id': 1369, 'author_profile': 'https://Stackoverflow.com/users/1369', 'pm_score': 11, 'selected': True, 'text': '<p>You can\'t query against the <code>DataTable</code>\'s <em>Rows</em> collection, since <code>DataRowCollection</code> doesn\'t implement <code>IEnumerable&lt;T&gt;</code>. You need to use the <code>AsEnumerable()</code> extension for <code>DataTable</code>. Like so:</p>\n<pre><code>var results = from myRow in myDataTable.AsEnumerable()\nwhere myRow.Field&lt;int&gt;(&quot;RowNo&quot;) == 1\nselect myRow;\n</code></pre>\n<p>And as <a href="https://stackoverflow.com/a/10893/5519709">@Keith</a> says, you\'ll need to add a reference to <a href="http://msdn.microsoft.com/en-us/library/system.data.datarowextensions.aspx" rel="noreferrer">System.Data.DataSetExtensions</a></p>\n<p><code>AsEnumerable()</code> returns <code>IEnumerable&lt;DataRow&gt;</code>. If you need to convert <code>IEnumerable&lt;DataRow&gt;</code> to a <code>DataTable</code>, use the <code>CopyToDataTable()</code> extension.</p>\n<p>Below is query with Lambda Expression,</p>\n<pre><code>var result = myDataTable\n    .AsEnumerable()\n    .Where(myRow =&gt; myRow.Field&lt;int&gt;(&quot;RowNo&quot;) == 1);\n</code></pre>\n'}, {'answer_id': 613431, 'author': 'JoelFan', 'author_id': 16012, 'author_profile': 'https://Stackoverflow.com/users/16012', 'pm_score': 7, 'selected': False, 'text': '<pre><code>var results = from DataRow myRow in myDataTable.Rows\n    where (int)myRow["RowNo"] == 1\n    select myRow\n</code></pre>\n'}, {'answer_id': 2890640, 'author': 'Ravi', 'author_id': 348127, 'author_profile': 'https://Stackoverflow.com/users/348127', 'pm_score': 5, 'selected': False, 'text': '<pre><code>var query = from p in dt.AsEnumerable()\n                    where p.Field&lt;string&gt;("code") == this.txtCat.Text\n                    select new\n                    {\n                        name = p.Field&lt;string&gt;("name"),\n                        age= p.Field&lt;int&gt;("age")                         \n                    };\n</code></pre>\n\n<p>the name and age fields are now part of the query object and can be accessed like so: <strong>Console.WriteLine(query.name);</strong></p>\n'}, {'answer_id': 6678063, 'author': 'Salim', 'author_id': 842567, 'author_profile': 'https://Stackoverflow.com/users/842567', 'pm_score': 5, 'selected': False, 'text': '<p><a href="http://dotnetarchitect.wordpress.com/2009/03/18/using-linq-to-manipulate-data-in-datasetdatatable/">Using LINQ to manipulate data in DataSet/DataTable</a></p>\n\n<pre><code>var results = from myRow in tblCurrentStock.AsEnumerable()\n              where myRow.Field&lt;string&gt;("item_name").ToUpper().StartsWith(tbSearchItem.Text.ToUpper())\n              select myRow;\nDataView view = results.AsDataView();\n</code></pre>\n'}, {'answer_id': 8739712, 'author': 'sushil pandey', 'author_id': 843294, 'author_profile': 'https://Stackoverflow.com/users/843294', 'pm_score': 5, 'selected': False, 'text': '<pre><code>//Create DataTable \nDataTable dt= new DataTable();\ndt.Columns.AddRange(new DataColumn[]\n{\n   new DataColumn("ID",typeof(System.Int32)),\n   new DataColumn("Name",typeof(System.String))\n\n});\n\n//Fill with data\n\ndt.Rows.Add(new Object[]{1,"Test1"});\ndt.Rows.Add(new Object[]{2,"Test2"});\n\n//Now  Query DataTable with linq\n//To work with linq it should required our source implement IEnumerable interface.\n//But DataTable not Implement IEnumerable interface\n//So we call DataTable Extension method  i.e AsEnumerable() this will return EnumerableRowCollection&lt;DataRow&gt;\n\n\n// Now Query DataTable to find Row whoes ID=1\n\nDataRow drow = dt.AsEnumerable().Where(p=&gt;p.Field&lt;Int32&gt;(0)==1).FirstOrDefault();\n // \n</code></pre>\n'}, {'answer_id': 10648288, 'author': 'midhun sankar', 'author_id': 1402739, 'author_profile': 'https://Stackoverflow.com/users/1402739', 'pm_score': 4, 'selected': False, 'text': '<p>Try this</p>\n\n<pre><code>var row = (from result in dt.AsEnumerable().OrderBy( result =&gt; Guid.NewGuid()) select result).Take(3) ; \n</code></pre>\n'}, {'answer_id': 12938526, 'author': 'Abdul Saboor', 'author_id': 1176903, 'author_profile': 'https://Stackoverflow.com/users/1176903', 'pm_score': 3, 'selected': False, 'text': '<p>For VB.NET The code will look like this:</p>\n\n<pre><code>Dim results = From myRow In myDataTable  \nWhere myRow.Field(Of Int32)("RowNo") = 1 Select myRow\n</code></pre>\n'}, {'answer_id': 16198286, 'author': 'xadriel', 'author_id': 618083, 'author_profile': 'https://Stackoverflow.com/users/618083', 'pm_score': 4, 'selected': False, 'text': "<p>Most likely, the classes for the DataSet, DataTable and DataRow are already defined in the solution. If that's the case you won't need the DataSetExtensions reference.</p>\n\n<p>Ex. DataSet class name-> CustomSet, DataRow class name-> CustomTableRow (with defined columns: RowNo, ...)</p>\n\n<pre><code>var result = from myRow in myDataTable.Rows.OfType&lt;CustomSet.CustomTableRow&gt;()\n             where myRow.RowNo == 1\n             select myRow;\n</code></pre>\n\n<p>Or (as I prefer)</p>\n\n<pre><code>var result = myDataTable.Rows.OfType&lt;CustomSet.CustomTableRow&gt;().Where(myRow =&gt; myRow.RowNo);\n</code></pre>\n"}, {'answer_id': 19756035, 'author': 'AuthorProxy', 'author_id': 1763061, 'author_profile': 'https://Stackoverflow.com/users/1763061', 'pm_score': 3, 'selected': False, 'text': '<p>You can get it work elegant via linq like this:</p>\n\n<pre><code>from prod in TenMostExpensiveProducts().Tables[0].AsEnumerable()\nwhere prod.Field&lt;decimal&gt;("UnitPrice") &gt; 62.500M\nselect prod\n</code></pre>\n\n<p>Or like dynamic linq this (AsDynamic is called directly on DataSet):</p>\n\n<pre><code>TenMostExpensiveProducts().AsDynamic().Where (x =&gt; x.UnitPrice &gt; 62.500M)\n</code></pre>\n\n<p>I prefer the last approach while is is the most flexible.\nP.S.: Don\'t forget to connect <code>System.Data.DataSetExtensions.dll</code> reference</p>\n'}, {'answer_id': 21497646, 'author': 'Vinay', 'author_id': 2074385, 'author_profile': 'https://Stackoverflow.com/users/2074385', 'pm_score': 3, 'selected': False, 'text': '<pre><code>var results = from myRow in myDataTable\nwhere results.Field&lt;Int32&gt;("RowNo") == 1\nselect results;\n</code></pre>\n'}, {'answer_id': 22985291, 'author': 'Uthaiah', 'author_id': 1488323, 'author_profile': 'https://Stackoverflow.com/users/1488323', 'pm_score': 3, 'selected': False, 'text': '<p>Try this... </p>\n\n<pre><code>SqlCommand cmd = new SqlCommand( "Select * from Employee",con);\nSqlDataReader dr = cmd.ExecuteReader( );\nDataTable dt = new DataTable( "Employee" );\ndt.Load( dr );\nvar Data = dt.AsEnumerable( );\nvar names = from emp in Data select emp.Field&lt;String&gt;( dt.Columns[1] );\nforeach( var name in names )\n{\n    Console.WriteLine( name );\n}\n</code></pre>\n'}, {'answer_id': 26367127, 'author': 'LandedGently', 'author_id': 103965, 'author_profile': 'https://Stackoverflow.com/users/103965', 'pm_score': 3, 'selected': False, 'text': '<p>In my application I found that using LINQ to Datasets with the AsEnumerable() extension for DataTable as suggested in the answer was extremely slow.  If you\'re interested in optimizing for speed, use James Newtonking\'s Json.Net library (<a href="http://james.newtonking.com/json/help/index.html" rel="noreferrer">http://james.newtonking.com/json/help/index.html</a>)</p>\n\n<pre><code>// Serialize the DataTable to a json string\nstring serializedTable = JsonConvert.SerializeObject(myDataTable);    \nJarray dataRows = Jarray.Parse(serializedTable);\n\n// Run the LINQ query\nList&lt;JToken&gt; results = (from row in dataRows\n                    where (int) row["ans_key"] == 42\n                    select row).ToList();\n\n// If you need the results to be in a DataTable\nstring jsonResults = JsonConvert.SerializeObject(results);\nDataTable resultsTable = JsonConvert.DeserializeObject&lt;DataTable&gt;(jsonResults);\n</code></pre>\n'}, {'answer_id': 29133713, 'author': 'Matt Kemp', 'author_id': 631277, 'author_profile': 'https://Stackoverflow.com/users/631277', 'pm_score': 4, 'selected': False, 'text': '<p>This is a simple way that works for me and uses lambda expressions:</p>\n\n<pre><code>var results = myDataTable.Select("").FirstOrDefault(x =&gt; (int)x["RowNo"] == 1)\n</code></pre>\n\n<p>Then if you want a particular value:</p>\n\n<pre><code>if(results != null) \n    var foo = results["ColName"].ToString()\n</code></pre>\n'}, {'answer_id': 31803241, 'author': 'Iman', 'author_id': 184572, 'author_profile': 'https://Stackoverflow.com/users/184572', 'pm_score': 3, 'selected': False, 'text': '<pre><code>IEnumerable&lt;string&gt; result = from myRow in dataTableResult.AsEnumerable()\n                             select myRow["server"].ToString() ;\n</code></pre>\n'}, {'answer_id': 35164023, 'author': 'vandsh', 'author_id': 2242217, 'author_profile': 'https://Stackoverflow.com/users/2242217', 'pm_score': 6, 'selected': False, 'text': '<p>I realize this has been answered a few times over, but just to offer another approach:</p>\n<p>I like to use the <code>.Cast&lt;T&gt;()</code> method, it helps me maintain sanity in seeing the explicit type defined and deep down I think <code>.AsEnumerable()</code> calls it anyways:</p>\n<pre class="lang-cs prettyprint-override"><code>var results = from myRow in myDataTable.Rows.Cast&lt;DataRow&gt;() \n                  where myRow.Field&lt;int&gt;(&quot;RowNo&quot;) == 1 select myRow;\n</code></pre>\n<p>or</p>\n<pre class="lang-cs prettyprint-override"><code>var results = myDataTable.Rows.Cast&lt;DataRow&gt;()\n                  .FirstOrDefault(x =&gt; x.Field&lt;int&gt;(&quot;RowNo&quot;) == 1);\n</code></pre>\n<p><em>As noted in comments, does not require <code>System.Data.DataSetExtensions</code> or any other assemblies (<a href="https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.cast" rel="noreferrer">Reference</a>)</em></p>\n'}, {'answer_id': 36422555, 'author': 'Mohit Verma', 'author_id': 6049604, 'author_profile': 'https://Stackoverflow.com/users/6049604', 'pm_score': 5, 'selected': False, 'text': '<p>Try this simple line of query:</p>\n\n<pre><code>var result=myDataTable.AsEnumerable().Where(myRow =&gt; myRow.Field&lt;int&gt;("RowNo") == 1);\n</code></pre>\n'}, {'answer_id': 46937157, 'author': 'Ryan Gavin', 'author_id': 6294612, 'author_profile': 'https://Stackoverflow.com/users/6294612', 'pm_score': 3, 'selected': False, 'text': '<p>Example on how to achieve this provided below: </p>\n\n<pre><code>DataSet dataSet = new DataSet(); //Create a dataset\ndataSet = _DataEntryDataLayer.ReadResults(); //Call to the dataLayer to return the data\n\n//LINQ query on a DataTable\nvar dataList = dataSet.Tables["DataTable"]\n              .AsEnumerable()\n              .Select(i =&gt; new\n              {\n                 ID = i["ID"],\n                 Name = i["Name"]\n               }).ToList();\n</code></pre>\n'}, {'answer_id': 48572211, 'author': 'Gabriel Martinez Bustos', 'author_id': 6328328, 'author_profile': 'https://Stackoverflow.com/users/6328328', 'pm_score': 3, 'selected': False, 'text': '<p>you can try this, but you must be sure the type of values for each Column</p>\n\n<pre><code>List&lt;MyClass&gt; result = myDataTable.AsEnumerable().Select(x=&gt; new MyClass(){\n     Property1 = (string)x.Field&lt;string&gt;("ColumnName1"),\n     Property2 = (int)x.Field&lt;int&gt;("ColumnName2"),\n     Property3 = (bool)x.Field&lt;bool&gt;("ColumnName3"),    \n});\n</code></pre>\n'}, {'answer_id': 57558642, 'author': 'Alan', 'author_id': 10656609, 'author_profile': 'https://Stackoverflow.com/users/10656609', 'pm_score': 0, 'selected': False, 'text': '<p>I propose following solution:</p>\n\n<pre><code>DataView view = new DataView(myDataTable); \nview.RowFilter = "RowNo = 1";\nDataTable results = view.ToTable(true);\n</code></pre>\n\n<p>Looking at the <a href="https://learn.microsoft.com/de-de/dotnet/api/system.data.dataview?view=netframework-4.8" rel="nofollow noreferrer">DataView Documentation</a>, the first thing we can see is this:</p>\n\n<blockquote>\n  <p>Represents a databindable, customized view of a DataTable for sorting, filtering, searching, editing, and navigation.</p>\n</blockquote>\n\n<p>What I am getting from this is that DataTable is meant to only store data and DataView is there enable us to "query" against the DataTable. </p>\n\n<p>Here is how this works in this particular case:</p>\n\n<p>You try to implement the SQL Statement</p>\n\n<pre><code>SELECT *\nFROM myDataTable\nWHERE RowNo = 1\n</code></pre>\n\n<p>in "DataTable language". In C# we would read it like this:</p>\n\n<pre><code>FROM myDataTable\nWHERE RowNo = 1\nSELECT *\n</code></pre>\n\n<p>which looks in C# like this:</p>\n\n<pre><code>DataView view = new DataView(myDataTable);  //FROM myDataTable\nview.RowFilter = "RowNo = 1";  //WHERE RowNo = 1\nDataTable results = view.ToTable(true);  //SELECT *\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/10855', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/445/']