Thursday, May 1, 2008

Basic sample of LINQ

Here is an sample which helps in understanding LINQ better..

In this sample we will list the items in the inventory and search for the items that are finished.



using System;
using System.Linq;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Products[] ProductsList = {
new Products(){ Name = "Laptop", RemainingCount = 1},
new Products(){ Name = "CD", RemainingCount = 0},
new Products{ Name = "DVD", RemainingCount = 0},
new Products{ Name = "Cabinet", RemainingCount = 2}
};

Console.WriteLine("Total Inventory Items ::");

var Inventory = from Product in ProductsList
orderby Product.Name
select new { Name = Product.Name, RemCount = Product.RemainingCount };

foreach (var Item in Inventory)
Console.WriteLine(" Inventory has {0} peice of {1}", Item.RemCount, Item.Name );

Console.WriteLine();
Console.WriteLine();

Console.WriteLine("Empty Inventory Items ::");

var EmptyInventory = from Product in ProductsList
orderby Product.Name
where Product.RemainingCount == 0
select new { Product.Name};

foreach (var Item in EmptyInventory)
Console.WriteLine(" {0}", Item.Name);

Console.Read();
}

class Products
{
public string Name{get; set;}
public int RemainingCount{get; set;}
}
}
}



Hope you got the example executed..

For More LINQ Functions click here

Keep Learning

No comments: