Getting started with LINQ in C#

What is LINQ? LINQ stands for Language Integrated Query. LINQ defines keywords that you can use to select, filter, sort, group, and transform data.

The minor miracle of LINQ is that different LINQ providers allow these keywords to work with different types of data.

LINQ to Objects, LINQ to DataSet, LINQ to XML, LINQ to SQL, LINQ to Entities.

How to write LINQ-
Suppose there is a List of Product.
List<Product> product = new List<Product>();
Create object and add items to the List.
LINQ to get all product starts with Letter C.
var result = from Product in product
                      where Product.productname.StartsWith(“C”)
                      select Product;

All LINQ expressions must have a  from clause that indicates the data source and a  select clause that indicates the data you want to retrieve
var result = from Product in product …..;

Filter data with LINQ

var result = from Product in product  
          where Product.unitavailable > 0 && Product.UnitPrice > 15000  
           select Product;

You may call your own created method in LINQ expression-

private bool TestData(Product product) {     return product.productname.StartsWith(“C”); }

 var result = from Product in product
                      where TestData(Product)
                      select Product;

Sorting With LINQ expression-

var result = from Product in product            
orderby Product.productname, Product.productid descending
             select Product; 

Leave a Comment

RSS
YouTube
YouTube
Instagram