Resources » Code Snippets » LINQ Samples

Filtering data table using LINQ query


Posted Date:     Category: LINQ Samples    
Author: Member Level: Bronze    Points: 20


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("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)
{
Console.Write(name);
}



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





Did you like this resource? Share it with your friends and show your love!


Responses to "Filtering data table using LINQ query"

No responses found. Be the first to respond...

Feedbacks      

Post Comment:




  • 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:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Next Resource: How to write Fluent Linq Queries?
    Previous Resource: Restriction and Projection Operators in LINQ
    Return to Resources
    Post New Resource
    Category: LINQ Samples


    Post resources and earn money!
     
    More Resources
    Popular Tags   Tag posting guidelines   Search Tags  
    (No tags found.)
    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India
    2005 - 2012 All Rights Reserved.
    .NET and other trademarks mentioned in this site belong to Microsoft and other respective trademark owners.
    Articles, tutorials and all other content offered here is for educational purpose only.
    We are not associated with Microsoft or its partners.