Filtering data table using LINQ query

LINQ can be used on data tables to filter out those rows from the data table which matches the filter criteria. LINQ query improves performance as compared to traditional Select() method on data table.

Lets take an example of Employees data table which contains two columns "Name" and "Salary".

DataTable dtEmployees = new DataTable();

//Columns of data table
dtEmployees.Columns.Add("Name", typeof(string));
dtEmployees.Columns.Add("Salary", typeof(double));

//Adding some rows in the data table
dtEmployees.Rows.Add("John", 50000);
dtEmployees.Rows.Add("Jai", 15000);

Now I want to get Name of Employees whose salary is more than 20000.
To achieve this kind of requirement, follow below LINQ statement.

var result = from row in dtEmployees.AsEnumerable()
where row.Field("Salary") > 20000
select row.Field("Name");

result is a collection of rows of employees whose salary is greater than 20000.

To retrieve employee name from result variable

foreach (string name in result)

Out put would be John and Joseph, because John and Joseph's salary is greater than 20000.


Author: Phagu Mahato22 Jan 2014 Member Level: Gold   Points : 7

You can follow following Steps for
1.) You can use the DataTable.Select method. However, the results are an array of DataRow which is not bindable.
2.) You can use a DataView which is efficient for sorting, filtering. All DataTables have a default DataView -- DataTable.DefaultView
3.) Or you can use LINQ.
Sample code as below

DataView dv = new DataView(tableOne, "ProductID <> 'PDXX'", "ProductTime desc", DataViewRowState.CurrentRows);

Or transform the DataView back to a DataTable
DataTable newTable = new DataView(tableOne, "ProductID <> 'PDXX'",
"ProductTime desc", DataViewRowState.CurrentRows).ToTable();

Or you can use LINQ
IEnumerable Producted = tableOne.AsEnumerable()
.Where(i => i.Field("ProductID ") != 'PDXX')
.ProductByDescending(i => i.Field("ProductTime "));

Or use LINQ to transform it to a DataTable
DataTable newTable = tableOne.AsEnumerable()
.Where(i => i.Field("ProductID ") != 'PDXX')
.ProductByDescending(i => i.Field("ProductTime "))

Author: Umesh Bhosale21 Apr 2014 Member Level: Silver   Points : 0

Hello All

you can simply use"");
which will return DataRow collection you will iterate through it and get required data..


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: