Monday, 23 July 2012

Linq operations & Lamda Expressions syntax with simple examples:


LINQ is a cool feature in C# 3.0. Most of the developers are struggling for the syntax and examples. Here I have collected various examples for each operator in LINQ and the equivalent Lambda Expressions.

Where

IEnumerable x = products.Where(p => p.UnitPrice >= 10);
IEnumerable x =
from p in products
where p.UnitPrice >= 10
select p;

Select
 
IEnumerable productNames = products.Select(p => p.Name);
IEnumerable productNames = from p in products select p.Name;
var namesAndPrices =
products.
Where(p => p.UnitPrice >= 10).
Select(p => new { p.Name, p.UnitPrice }).
ToList();
IEnumerable indices =
products.
Select((product, index) => new { product, index }).
Where(x => x.product.UnitPrice >= 10).
Select(x => x.index);

SelectMany

IEnumerable orders =
customers.
Where(c => c.Country == "Denmark").
SelectMany(c => c.Orders);
var namesAndOrderIDs =
customers.
Where(c => c.Country == "Denmark").
SelectMany(c => c.Orders).
Where(o => o.OrderDate.Year == 2005).
Select(o => new { o.Customer.Name, o.OrderID });
var namesAndOrderIDs =
customers.
Where(c => c.Country == "Denmark").
SelectMany(c => c.Orders, (c,o) => new { c, o }).
Where(co => co.o.OrderDate.Year == 2005).
Select(co => new { co.c.Name, co.o.OrderID });
var namesAndOrderIDs =
from c in customers
where c.Country == "Denmark"
from o in c.Orders
where o.OrderDate.Year == 2005
select new { c.Name, o.OrderID };

Take

IEnumerable MostExpensive10 =
products.OrderByDescending(p => p.UnitPrice).Take(10);

Skip

IEnumerable AllButMostExpensive10 =
products.OrderByDescending(p => p.UnitPrice).Skip(10);
TakeWhile SkipWhile
s.TakeWhile(p) s.SkipWhile(p)

Join

var custOrders =
customers.
Join(orders, c => c.CustomerID, o => o.CustomerID,
(c, o) => new { c.Name, o.OrderDate, o.Total });
var custOrders =
from c in customers
join o in orders on c.CustomerID equals o.CustomerID
select new { c.Name, o.OrderDate, o.Total };

GroupJoin

var custTotalOrders =
customers.
GroupJoin(orders, c => c.CustomerID, o => o.CustomerID,
(c, co) => new { c.Name, TotalOrders = co.Sum(o => o.Total) });
var custTotalOrders =
from c in customers
join o in orders on c.CustomerID equals o.CustomerID into co
select new { c.Name, TotalOrders = co.Sum(o => o.Total) };
var custTotalOrders =
from c in customers
join o in orders on c.CustomerID equals o.CustomerID
select new { c.Name, o.OrderDate, o.Total };
var custTotalOrders =
from c in customers
join o in orders on c.CustomerID equals o.CustomerID into co
from o in co
select new { c.Name, o.OrderDate, o.Total };
var custTotalOrders =
from c in customers
join o in orders on c.CustomerID equals o.CustomerID into co
from o in co.DefaultIfEmpty(emptyOrder)
select new { c.Name, o.OrderDate, o.Total };

Concat

IEnumerable locations =
customers.Select(c => c.City).
Concat(customers.Select(c => c.Region)).
Concat(customers.Select(c => c.Country)).
Distinct();
IEnumerable locations =
new[] {
customers.Select(c => c.City),
customers.Select(c => c.Region),
customers.Select(c => c.Country),}.
SelectMany(s => s).
Distinct();

OrderBy / ThenBy

IEnumerable orderedProducts1 =
products.
OrderBy(p => p.Category).
ThenByDescending(p => p.UnitPrice).
ThenBy(p => p.Name);
IEnumerable orderedProducts1 =
from p in products
orderby p.Category, p.UnitPrice descending, p.Name
select p;
IEnumerable orderedProducts2 =
products.
Where(p => p.Category == "Beverages").
OrderBy(p => p.Name, StringComparer.CurrentCultureIgnoreCase);
IEnumerable orderedProductNames =
products.
Where(p => p.Category == "Beverages").
Select(p => p.Name).
OrderBy(x => x);

GroupBy

IEnumerable<igrouping> productsByCategory =
products.GroupBy(p => p.Category);
IEnumerable<igrouping> productNamesByCategory =
products.GroupBy(p => p.Category, p => p.Name);

Distinct

IEnumerable productCategories =
products.Select(p => p.Category).Distinct();

AsEnumerable

Table custTable = GetCustomersTable();
var query = custTable.AsEnumerable().Where(c => IsGoodCustomer(c));

ToArray

string[] customerCountries =
customers.Select(c => c.Country).Distinct().ToArray();

ToList

List customersWithOrdersIn2005 =
customers.
Where(c => c.Orders.Any(o => o.OrderDate.Year == 2005)).
ToList();

ToDictionary

Dictionary orders =
customers.
SelectMany(c => c.Orders).
Where(o => o.OrderDate.Year == 2005).
ToDictionary(o => o.OrderID);
Dictionary categoryMaxPrice =
products.
GroupBy(p => p.Category).
ToDictionary(g => g.Key, g => g.Group.Max(p => p.UnitPrice));

ToLookup

Lookup productsByCategory =
products.ToLookup(p => p.Category);
IEnumerable beverages = productsByCategory["Beverage"];

OfType

List persons = GetListOfPersons();
IEnumerable employees = persons.OfType();

Cast

ArrayList objects = GetOrders();
IEnumerable ordersIn2005 =
objects.
Cast().
Where(o => o.OrderDate.Year == 2005);
ArrayList objects = GetOrders();
IEnumerable ordersIn2005 =
from Order o in objects
where o.OrderDate.Year == 2005
select o;

First

string phone = "206-555-1212";
Customer c = customers.First(c => c.Phone == phone);

Single

int id = 12345;
Customer c = customers.Single(c => c.CustomerID == id);

ElementAt

Product thirdMostExpensive =
products.OrderByDescending(p => p.UnitPrice).ElementAt(2);

Range

int[] squares = Enumerable.Range(0, 100).Select(x => x * x).ToArray();

Repeat

long[] x = Enumerable.Repeat(-1L, 256).ToArray();

Empty

IEnumerable noCustomers = Enumerable.Empty();

Any

bool b = products.Any(p => p.UnitPrice >= 100 && p.UnitsInStock == 0);

All

IEnumerable fullyStockedCategories =
products.
GroupBy(p => p.Category).
Where(g => g.Group.All(p => p.UnitsInStock > 0)).
Select(g => g.Key);

Count

int count = customers.Count(c => c.City == "London");

Sum

int year = 2005;
var namesAndTotals =
customers.
Select(c => new {
c.Name,
TotalOrders =
c.Orders.
Where(o => o.OrderDate.Year == year).
Sum(o => o.Total)});

Min

var minPriceByCategory =
products.
GroupBy(p => p.Category).
Select(g => new {
Category = g.Key,
MinPrice = g.Group.Min(p => p.UnitPrice)});

Max

decimal largestOrder =
customers.
SelectMany(c => c.Orders).
Where(o => o.OrderDate.Year == 2005).
Max(o => o.Total);

Average

var averageOrderTotals =
customers.
Select(c => new {
c.Name,
AverageOrderTotal = c.Orders.Average(o => o.Total)});

Aggregate

var longestNamesByCategory =
products.
GroupBy(p => p.Category).
Select(g => new {
Category = g.Key,
LongestName =
g.Group.
Select(p => p.Name).
Aggregate((s, t) => t.Length > s.Length ? t : s)
});


No comments:

Post a Comment