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("Joseph",25000);
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
select row.Field
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)
{
Console.Write(name);
}
Out put would be John and Joseph, because John and Joseph's salary is greater than 20000.
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