LINQ Operators and Lambda Expressions

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

  1. IEnumerable<Product> x = products.Where(p => p.UnitPrice >= 10);
  2. IEnumerable<Product> x =
  3. from p in products
  4. where p.UnitPrice >= 10
  5. select p;

Select

  1. IEnumerable<string> productNames = products.Select(p => p.Name);
  2. IEnumerable<string> productNames = from p in products select p.Name;
  3. var namesAndPrices =
  4. products.
  5. Where(p => p.UnitPrice >= 10).
  6. Select(p => new { p.Name, p.UnitPrice }).
  7. ToList();
  8. IEnumerable<int> indices =
  9. products.
  10. Select((product, index) => new { product, index }).
  11. Where(x => x.product.UnitPrice >= 10).
  12. Select(x => x.index);

SelectMany

  1. IEnumerable<Order> orders =
  2. customers.
  3. Where(c => c.Country == "Denmark").
  4. SelectMany(c => c.Orders);
  5. var namesAndOrderIDs =
  6. customers.
  7. Where(c => c.Country == "Denmark").
  8. SelectMany(c => c.Orders).
  9. Where(o => o.OrderDate.Year == 2005).
  10. Select(o => new { o.Customer.Name, o.OrderID });
  11. var namesAndOrderIDs =
  12. customers.
  13. Where(c => c.Country == "Denmark").
  14. SelectMany(c => c.Orders, (c,o) => new { c, o }).
  15. Where(co => co.o.OrderDate.Year == 2005).
  16. Select(co => new { co.c.Name, co.o.OrderID });
  17. var namesAndOrderIDs =
  18. from c in customers
  19. where c.Country == "Denmark"
  20. from o in c.Orders
  21. where o.OrderDate.Year == 2005
  22. select new { c.Name, o.OrderID };

Take

  1. IEnumerable<Product> MostExpensive10 =products.OrderByDescending(p => p.UnitPrice).Take(10);
Skip
  1. IEnumerable<Product> AllButMostExpensive10 = products.OrderByDescending(p => p.UnitPrice).Skip(10);
TakeWhile SkipWhile
  1. s.TakeWhile(p) s.SkipWhile(p)

Join

  1. var custOrders = customers.
  2. Join(orders, c => c.CustomerID, o => o.CustomerID, (c, o) => new {
  3. c.Name, o.OrderDate, o.Total
  4. });
  5. var custOrders = from c in customers
  6. join o in orders on c.CustomerID equals o.CustomerID
  7. select new {
  8. c.Name, o.OrderDate, o.Total
  9. };
GroupJoin
  1. var custTotalOrders = customers.
  2. GroupJoin(orders, c => c.CustomerID, o => o.CustomerID, (c, co) => new {
  3. c.Name, TotalOrders = co.Sum(o => o.Total)
  4. });
  5. var custTotalOrders = from c in customers
  6. join o in orders on c.CustomerID equals o.CustomerID into co
  7. select new {
  8. c.Name, TotalOrders = co.Sum(o => o.Total)
  9. };
  10. var custTotalOrders = from c in customers
  11. join o in orders on c.CustomerID equals o.CustomerID
  12. select new {
  13. c.Name, o.OrderDate, o.Total
  14. };
  15. var custTotalOrders = from c in customers
  16. join o in orders on c.CustomerID equals o.CustomerID into co
  17. from o in co
  18. select new {
  19. c.Name, o.OrderDate, o.Total
  20. };
  21. var custTotalOrders = from c in customers
  22. join o in orders on c.CustomerID equals o.CustomerID into co
  23. from o in co.DefaultIfEmpty(emptyOrder)
  24. select new {
  25. c.Name, o.OrderDate, o.Total
  26. };

Concat

  1. IEnumerable < string > locations = customers.Select(c => c.City).
  2. Concat(customers.Select(c => c.Region)).
  3. Concat(customers.Select(c => c.Country)).
  4. Distinct();
  5. IEnumerable < string > locations = new [] {
  6. customers.Select(c => c.City),
  7. customers.Select(c => c.Region),
  8. customers.Select(c => c.Country),
  9. }.
  10. SelectMany(s => s).
  11. Distinct();

OrderBy / ThenBy

  1. IEnumerable<Product> orderedProducts1 =
  2. products.
  3. OrderBy(p => p.Category).
  4. ThenByDescending(p => p.UnitPrice).
  5. ThenBy(p => p.Name);
  6. IEnumerable<Product> orderedProducts1 =
  7. from p in products
  8. orderby p.Category, p.UnitPrice descending, p.Name
  9. select p;
  10. IEnumerable<Product> orderedProducts2 =
  11. products.
  12. Where(p => p.Category == "Beverages").
  13. OrderBy(p => p.Name, StringComparer.CurrentCultureIgnoreCase);
  14. IEnumerable<string> orderedProductNames =
  15. products.
  16. Where(p => p.Category == "Beverages").
  17. Select(p => p.Name).
  18. OrderBy(x => x);
GroupBy
  1. IEnumerable<IGrouping<string, Product>> productsByCategory =products.GroupBy(p => p.Category);
  2. IEnumerable<IGrouping<string, string>> productNamesByCategory =products.GroupBy(p => p.Category, p => p.Name);
Distinct
  1. IEnumerable<string> productCategories =products.Select(p => p.Category).Distinct();
AsEnumerable
  1. Table<Customer> custTable = GetCustomersTable();
  2. var query = custTable.AsEnumerable().Where(c => IsGoodCustomer(c));
ToArray
  1. string[] customerCountries =customers.Select(c => c.Country).Distinct().ToArray();
ToList
  1. List<Customer> customersWithOrdersIn2005 =customers.
  2. Where(c => c.Orders.Any(o => o.OrderDate.Year == 2005)).
  3. ToList();
ToDictionary
  1. Dictionary<int,Order> orders =customers.
  2. SelectMany(c => c.Orders).
  3. Where(o => o.OrderDate.Year == 2005).
  4. ToDictionary(o => o.OrderID);
  5. Dictionary<string,decimal> categoryMaxPrice =products.
  6. GroupBy(p => p.Category).
  7. ToDictionary(g => g.Key, g => g.Group.Max(p => p.UnitPrice));
ToLookup
  1. Lookup<string,Product> productsByCategory =products.ToLookup(p => p.Category);
  2. IEnumerable<Product> beverages = productsByCategory["Beverage"];
OfType
  1. List<Person> persons = GetListOfPersons();
  2. IEnumerable<Employee> employees = persons.OfType<Employee>();
Cast
  1. ArrayList objects = GetOrders();
  2. IEnumerable<Order> ordersIn2005 =
  3. objects.
  4. Cast<Order>().
  5. Where(o => o.OrderDate.Year == 2005);
  6. ArrayList objects = GetOrders();
  7. IEnumerable<Order> ordersIn2005 =
  8. from Order o in objects
  9. where o.OrderDate.Year == 2005
  10. select o;
First
  1. string phone = "206-555-1212";
  2. Customer c = customers.First(c => c.Phone == phone);
Single
  1. int id=12345;
  2. Customer c = customers.Single(c => c.CustomerID == id);
ElementAt
  1. Product thirdMostExpensive = products.OrderByDescending(p => p.UnitPrice).ElementAt(2);
Range
  1. int[] squares = Enumerable.Range(0, 100).Select(x => x * x).ToArray();

Repeat

  1. long[] x = Enumerable.Repeat(-1L, 256).ToArray();
Empty
  1. IEnumerable<Customer> noCustomers = Enumerable.Empty<Customer>();
Any
  1. bool b = products.Any(p => p.UnitPrice >= 100 && p.UnitsInStock == 0);
All
  1. IEnumerable<string> fullyStockedCategories =products.
  2. GroupBy(p => p.Category).
  3. Where(g => g.Group.All(p => p.UnitsInStock > 0)).
  4. Select(g => g.Key);
Count
  1. int count = customers.Count(c => c.City == "London");
Sum
  1. int year = 2005;
  2. var namesAndTotals = customers.
  3. Select(c => new {
  4. c.Name,
  5. TotalOrders = c.Orders.
  6. Where(o => o.OrderDate.Year == year).
  7. Sum(o => o.Total)
  8. });
Min
  1. var minPriceByCategory = products.
  2. GroupBy(p => p.Category).
  3. Select(g => new {
  4. Category = g.Key,
  5. MinPrice = g.Group.Min(p => p.UnitPrice)
  6. });
Max
  1. decimal largestOrder = customers.
  2. SelectMany(c => c.Orders).
  3. Where(o => o.OrderDate.Year == 2005).
  4. Max(o => o.Total);
Average
  1. var averageOrderTotals = customers.
  2. Select(c => new {
  3. c.Name,
  4. AverageOrderTotal = c.Orders.Average(o => o.Total)
  5. });
Aggregate
  1. var longestNamesByCategory = products.
  2. GroupBy(p => p.Category).
  3. Select(g => new {
  4. Category = g.Key,
  5. LongestName = g.Group.
  6. Select(p => p.Name).
  7. Aggregate((s, t) => t.Length > s.Length ? t : s)
  8. });