Monday, April 13, 2015

LINQ Operators and Lambda Expression - Syntax & 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<Product> x = products.Where(p => p.UnitPrice >= 10);
IEnumerable<Product> x =
    from p in products
    where p.UnitPrice >= 10
    select p;

Select
IEnumerable<string> productNames = products.Select(p => p.Name);
IEnumerable<string> 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<int> indices =
    products.
    Select((product, index) => new { product, index }).
    Where(x => x.product.UnitPrice >= 10).
    Select(x => x.index);

SelectMany

IEnumerable<Order> 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<Product> MostExpensive10 =
    products.OrderByDescending(p => p.UnitPrice).Take(10);

Skip

IEnumerable<Product> 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<string> locations =
    customers.Select(c => c.City).
    Concat(customers.Select(c => c.Region)).
    Concat(customers.Select(c => c.Country)).
    Distinct();
IEnumerable<string> locations =
    new[] {
        customers.Select(c => c.City),
        customers.Select(c => c.Region),
        customers.Select(c => c.Country),
    }.
    SelectMany(s => s).
    Distinct();

OrderBy / ThenBy

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

GroupBy

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

Distinct

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

AsEnumerable

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

ToArray

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

ToList

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

ToDictionary

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

ToLookup

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

OfType

List<Person> persons = GetListOfPersons();
IEnumerable<Employee> employees = persons.OfType<Employee>();

Cast

      ArrayList objects = GetOrders();
IEnumerable<Order> ordersIn2005 =
    objects.
    Cast<Order>().
    Where(o => o.OrderDate.Year == 2005);
ArrayList objects = GetOrders();
IEnumerable<Order> 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<Customer> noCustomers = Enumerable.Empty<Customer>();

Any

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

All

IEnumerable<string> 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