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:
For VB.NET The code will look like this:
Dim results = From myRow In myDataTable
Where myRow.Field(Of Int32)("RowNo") = 1 Select myRow
As @ch00k said:
using System.Data; //needed for the extension methods to work
...
var results =
from myRow in myDataTable.Rows
where myRow.Field<int>("RowNo") == 1
select myRow; //select the thing you want, not the collection
You also need to add a project reference to System.Data.DataSetExtensions
This is a simple way that works for me and uses lambda expressions:
var results = myDataTable.Select("").FirstOrDefault(x => (int)x["RowNo"] == 1)
Then if you want a particular value:
if(results != null)
var foo = results["ColName"].ToString()
var results = from DataRow myRow in myDataTable.Rows
where (int)myRow["RowNo"] == 1
select myRow
You can use LINQ to objects on the Rows collection, like so:
var results = from myRow in myDataTable.Rows where myRow.Field("RowNo") == 1 select myRow;
I propose following solution:
DataView view = new DataView(myDataTable);
view.RowFilter = "RowNo = 1";
DataTable results = view.ToTable(true);
Looking at the DataView Documentation, the first thing we can see is this:
Represents a databindable, customized view of a DataTable for sorting, filtering, searching, editing, and navigation.
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.
Here is how this works in this particular case:
You try to implement the SQL Statement
SELECT *
FROM myDataTable
WHERE RowNo = 1
in "DataTable language". In C# we would read it like this:
FROM myDataTable
WHERE RowNo = 1
SELECT *
which looks in C# like this:
DataView view = new DataView(myDataTable); //FROM myDataTable
view.RowFilter = "RowNo = 1"; //WHERE RowNo = 1
DataTable results = view.ToTable(true); //SELECT *