Menu ▼

Previous Next

LINQ to Lists :

In this example we will write LINQ queries on Lists, the advantage of linq is we no need to execute/initialize the linq query every time, initialize once and use where ever required. The below example willl explain how it will work.

LINQ Query :
Below LINQ query will find the products which are having price between 5000 and 10000 from Products list.

public class Products

{

    private string _productName;

    private string _category;

    private decimal _price;

 

    public string ProductName

    {

        get { return _productName; }

        set { _productName = value; }

    }

 

    public string Category

    {

        get { return _category; }

        set { _category = value; }

    }

 

    public decimal Price

    {

        get { return _price; }

        set { _price = value; }

    }

 

}

 

List<Products> listProducts = new List<Products>();

listProducts.Add(new Products { ProductName = "Mobile", Category = "Electronics", Price = 6000 });

listProducts.Add(new Products { ProductName = "Fridge", Category = "Electronics", Price = 12000 });

listProducts.Add(new Products { ProductName = "Chair", Category = "HomeNeeds", Price = 1000 });

listProducts.Add(new Products { ProductName = "Table", Category = "HomeNeeds", Price = 6000 });

listProducts.Add(new Products { ProductName = "T-Shirt", Category = "Clothes", Price = 1500 });

listProducts.Add(new Products { ProductName = "Jeans", Category = "Clothes", Price = 3500 });

 

var proudcts = from products in listProducts

                where products.Price > 5000 && products.Price < 10000

                orderby products.Price

                select new { products.ProductName, products.Category, products.Price };

gvproducts1.DataSource = proudcts;

gvproducts1.DataBind();

 


Output :
ProductNameCategoryPrice
MobileElectronics6000
TableHomeNeeds6000

LINQ Query :
Now we will add two more proudcts to the Products list, but without initalizing the linq query the old variable products will give you the latest records.

listProducts.Add(new Products { ProductName = "Water Purifier", Category = "HomeNeeds", Price = 8000 });

listProducts.Add(new Products { ProductName = "TV", Category = "Electronics", Price = 15000 });

 

gvproducts2.DataSource = proudcts;

gvproducts2.DataBind();

 


Output :
ProductNameCategoryPrice
MobileElectronics6000
TableHomeNeeds6000
Water PurifierHomeNeeds8000
Previous Next




Search dotnetlearners.com