We usually retrieve all products from a table. But sometimes we have a specific field or one more fields from a table. It can be done in very easy ways by using linq. Firs we will retrieve all fields from a table by using linq then we will find one more field from a table.
Get all products from Product table. We have class Product.
public class Product{
public string Name { get; set; }
public int Price { get; set; }
public string Unit { get; set; }
public string ProductType { get; set; }
public Product RelatedProduct { get; set; }
}
List<Product> products = new List<Product>(){
new Product(){
Name = "Laptop",
Price = "1000",
Unit ="pcs",
ProductType = "Computer"
},
new Product(){
Name = "Desktop",
Price = "2000",
Unit ="pcs",
ProductType = "Computer"
},
new Product(){
Name = "Mouse",
Price = "300",
Unit ="pcs",
ProductType = "Electronics"
},
new Product(){
Name = "Keyboard",
Price = "500",
Unit ="pcs",
ProductType = "Computer"
},
new Product(){
Name = "Power Strip",
Price = "400",
Unit ="pcs",
ProductType = "electronics"
},
};
var prod = from p in products select p;
//By using where statement
var prod = from p in products
where(p.Price >200 && p.Price < 100000)
select p;
foreach (var item in prod)
{
Console.WriteLine(item.Name);
}
// Select multiple fields
var prod = from p in products
where(p.Price >200 && p.Price < 100000)
select new{ productName=p.Name, productPrice=p.price};
foreach (var item in prod)
{
Console.WriteLine(item.productName + " " + item.productPrice);
}