linq tutorial

Referred from URL: - http://www.programmersheaven.com/2/CSharp3-4

Linq is short for Language Integrated Query. Imagine we have a list of orders. For this example, we will imagine they are stored in memory, We want to get a list of the costs of all orders that were placed by the Supplier identified by the number 25.

Reading from Memory
List Found = new List();
foreach (Order o in Orders)
if (o.SupplierID == 25)
Found.Add(o.Cost);

SQL Query
SELECT Cost FROM Orders WHERE SupplierID = 25

Linq query
var Found = from o in Orders
where o.SupplierID == 25
select o.Cost;
OutPut
Cost: 159.12
Cost: 2.89

Adding More Columns for returning
var Found = from o in Orders
where o.SupplierID == 84
select new { o.OrderID, o.Cost };

A Few More Simple Queries
var Found = from o in Orders
where o.SupplierID == 84 && o.Cost > 100
select new {
o.OrderID,
o.Cost,
CostWithTax = o.Cost * 1.1
};

Ordering
var Found = from o in Orders
where o.CustomerID == 84
orderby o.Cost ascending
select new { o.OrderID, o.Cost };

Grouping
var OrdersByCustomer = from o in Orders
group o by o.CustomerID;

Joins
var Found = from o in Orders
join c in Customers on o.CustomerID equals c.CustomerID
select new { c.Name, o.OrderID, o.Cost };

Query Continuations
var OrderCounts = from o in Orders
group o by o.CustomerID into g
select new {
CustomerID = g.Key,
TotalOrders = g.Count()
};

You May Also Like

0 comments