Tuesday, 16 June 2015

LINQ Queries

http://weblogs.asp.net/scottgu/linq-to-sql-part-3-querying-our-database

http://www.albahari.com/nutshell/10linqmyths.aspx

https://blog.udemy.com/linq-select/

Monday, 6 January 2014

LINQ Examples 7

Aggregate operators- LINQ Count, Sum, Min, Max and Average operators 

[Description("This sample uses COUNT to get the number of Orders.")]
public void LinqToEntities23() {
  var query = _em1.Orders.Count();
  Assert.IsTrue(query == 830);
}

[Description("This sample uses COUNT to get the number of Orders placed by Customers in Mexico.")]
public void LinqToEntities24() {
  var query = _em1.Orders.Where(o => o.Customer.Address.Country == "Mexico").Count();
  Assert.IsTrue(query == 28);
}

[Description("This sample uses COUNT to get the number of Orders shipped to Mexico.")]
public void LinqToEntities25() {
  var query = _em1.Orders
      .Where(o => o.ShipCountry == "Mexico").Count();
  Assert.IsTrue(query == 28);
}

[Description("This sample uses SUM to find the total freight over all Orders.")]
public void LinqToEntities26() {
  var query = _em1.Orders.Select(o => o.Freight).Sum();
  Assert.IsTrue(query == 64942.69M);
}

[Description("This sample uses SUM to find the total number of units on order over all Products.")]
public void LinqToEntities27() {
  var query = _em1.Products.Sum(p => p.UnitsOnOrder);
  Assert.IsTrue(query == 780);
}

[Description("This sample uses SUM to find the total number of units on order over all Products out-of-stock.")]
public void LinqToEntities28() {
  var query = _em1.Products.Where(p => p.UnitsInStock == 0).Sum(p => p.UnitsOnOrder);
  Assert.IsTrue(query == 70);
}

[Description("This sample uses MIN to find the lowest unit price of any Product.")]
public void LinqToEntities29() {
  var query = _em1.Products.Select(p => p.UnitPrice).Min();
  Assert.IsTrue(query == 2.5M);
}

[Description("This sample uses MIN to find the lowest freight of any Order.")]
public void LinqToEntities30() {
  var query = _em1.Orders.Min(o => o.Freight);
  Assert.IsTrue(query == 0.02M);
}

[Description("This sample uses MIN to find the lowest freight of any Order shipped to Mexico.")]
public void LinqToEntities31() {
  var query = _em1.Orders.Where(o => o.ShipCountry == "Mexico").Min(o => o.Freight);
  Assert.IsTrue(query == 0.4M);
  var query2 = _em1.Orders.Where(o => o.ShipCountry == "Mexico").Select(o => o.Freight).Min();
  Assert.IsTrue(query2 == 0.4M);
}

[Description("This sample uses Min to find the Products that have the lowest unit price " +
    "in each category, and returns the result as an anonoymous type.")]
public void LinqToEntities32() {
  var query = from p in _em1.Products
              group p by p.Category.CategoryID into g
              orderby g.Key
              select new {
                CategoryID = g.Key,
                CheapestProducts =
                    from p2 in g
                    where p2.UnitPrice == g.Min(p3 => p3.UnitPrice)
                    select p2
              };

  var r = query.ToList();
  Assert.IsTrue(r.Count() == 8);
  Assert.IsTrue(r.First().CategoryID == 1);
  Assert.IsTrue(r.First().CheapestProducts.First().UnitPrice == 4.5M);
}

[Description("This sample uses MAX to find the latest hire date of any Employee.")]
public void LinqToEntities33() {
  var query = _em1.Employees.Select(e => e.HireDate).Max();
  Assert.IsTrue(query == new DateTime(1994, 11, 15));
}

[Description("This sample uses MAX to find the most units in stock of any Product.")]
public void LinqToEntities34() {
  var query = _em1.Products.Max(p => p.UnitsInStock);
  Assert.IsTrue(query == 125);
}

[Description("This sample uses MAX to find the most units in stock of any Product with CategoryID = 1.")]
public void LinqToEntities35() {
  var query = _em1.Products.Where(p => p.Category.CategoryID == 2).Max(p => p.UnitsInStock);
  Assert.IsTrue(query == 120);
}

[Description("This sample uses MAX to find the Products that have the " +
    "highest unit price in each category, and returns the result as an anonoymous type.")]
public void LinqToEntities36() {
  var query = from p in _em1.Products
              group p by p.Category.CategoryID into g
              orderby g.Key
              select new {
                g.Key,
                MostExpensiveProducts =
                    from p2 in g
                    where p2.UnitPrice == g.Max(p3 => p3.UnitPrice)
                    orderby p2.UnitPrice
                    select p2
              };

  var r = query.ToList();
  Assert.IsTrue(r.Count() == 8);
  Assert.IsTrue(r.First().Key == 1);
  Assert.IsTrue(r.First().MostExpensiveProducts.First().UnitPrice == 263.5M);
}

[Description("This sample uses AVERAGE to find the average freight of all Orders.")]
public void LinqToEntities37() {
  var query = _em1.Orders.Select(o => o.Freight).Average();
  Assert.IsTrue(query == 78.2442M);
}

[Description("This sample uses AVERAGE to find the average unit price of all Products.")]
public void LinqToEntities38() {
  var query = _em1.Products.Average(p => p.UnitPrice);
  Assert.IsTrue(query == 28.8663M);
}

[Description("This sample uses AVERAGE to find the average unit price of all Products with CategoryID = 1.")]
public void LinqToEntities39() {
  var query = _em1.Products.Where(p => p.Category.CategoryID == 1)
      .Average(p => p.UnitPrice);
  Assert.IsTrue(query == 37.9791M);
}

[Description("This sample uses AVERAGE to find the Products that have unit price higher than the average unit price of the category for each category.")]
public void LinqToEntities40() {

  var query = from p in _em1.Products
              group p by p.Category.CategoryID into g
              orderby g.Key descending
              select new {
                g.Key,
                ExpensiveProducts =
                    from p2 in g
                    where p2.UnitPrice > g.Average(p3 => p3.UnitPrice)
                    orderby p2.UnitPrice
                    select p2
              };

  var r = query.ToList();
  Assert.IsTrue(r.Count() == 8);
  Assert.IsTrue(r.First().Key == 8);
}

[Description("This sample uses AVERAGE to find the average unit price of each category.")]
public void LinqToEntities41() {
  var query = from p in _em1.Products
              group p by p.Category.CategoryID into g
              orderby g.Key descending
              select new {
                g.Key,
                Average = g.Average(p => p.UnitPrice)
              };
  Assert.IsTrue(query.ToList().First().Key == 8);
  Assert.IsTrue(query.First().Average == 20.6825M);
}

LINQ Examples 6

Projection operators

[Description("This samples uses SELECT to get all Customers as Entity Objects.")]
public void LinqToEntities11() {
  var query = from c in _em1.Customers
              select c;
  Assert.IsTrue(query.Count() == 91);
}

[Description("This samples uses SELECT to get all Customer Contact Names as Strings.")]
public void LinqToEntities12() {
  var query = from c in _em1.Customers
              orderby c.ContactName
              select c.ContactName;
  var r = query.ToList();
  Assert.IsTrue(r.First() == "Alejandra Camino");
}

[Description("This samples uses SELECT to get all Customer Contact Names as an anonoymous type.")]
public void LinqToEntities13() {
  var query = from c in _em1.Customers
              orderby c.CompanyName
              select new { c.ContactName };

  var r = query.ToList();
  Assert.IsTrue(r.First().ContactName == "Maria Anders");
}

[Description("This sample uses SELECT to get Orders as anonymous type")]
public void LinqToEntities14() {
  var query = from o in _em1.Orders
              where o.Customer.Address.City == "London"
              orderby o.OrderDate
              select new { o };

  var r = query.ToList();
  Assert.IsTrue(r.Count() == 46);
  Assert.IsTrue(r.First().o.OrderDate == new DateTime(1996, 8, 26));
}

[Description("This sample uses SELECT to get all Orders and associated Customers as anonymous type")]
public void LinqToEntities15() {
  _em1.DefaultQueryStrategy = QueryStrategy.DataSourceOnly;
  var query = from o in _em1.Orders
              where o.Customer.Address.City == "London"
              orderby o.Customer.CompanyName descending
              select new { o, o.Customer };

  var r = query.ToList();
  Assert.IsTrue(r.Count() == 46);
  Assert.IsTrue(r.First().Customer.CompanyName == "Seven Seas Imports");
}

[Description("This sample uses SELECTMANY to get all Orders for a Customer as a flat result")]
public void LinqToEntities16() {
  _em1.DefaultQueryStrategy = QueryStrategy.DataSourceOnly;
  var query = from c in _em1.Customers
              where c.CustomerID == "ALFKI"
              from o in c.Orders
              orderby o.OrderDate
              select o;

  var r = query.ToList();
  Assert.IsTrue(r.Count() == 6);
  Assert.IsTrue(r.First().OrderDate == new DateTime(1997, 8, 25));
}

[Description("This sample uses SELECTMANY to get all Orders for a Customer as a flat result as a method query")]
public void LinqToEntities17() {
  _em1.DefaultQueryStrategy = QueryStrategy.DataSourceOnly;
  var query = _em1.Customers.Where(cust => cust.CustomerID == "ALFKI")
      .SelectMany(cust => cust.Orders
          .OrderBy(o => o.OrderDate));

  var r = query.ToList();
  Assert.IsTrue(r.Count() == 6);
  Assert.IsTrue(r.First().OrderDate == new DateTime(1997, 8, 25));
}

[Description("This sample uses SELECTMANY to get all Orders for Customers in Denmark as a flat result")]
public void LinqToEntities18() {
  _em1.DefaultQueryStrategy = QueryStrategy.DataSourceOnly;
  var query = from c in _em1.Customers
              where c.Address.Country == "Denmark"
              from o in c.Orders
              orderby o.OrderDate
              select o;

  var r = query.ToList();
  Assert.IsTrue(r.Count() == 18);
  Assert.IsTrue(r.First().OrderDate == new DateTime(1996, 10, 29));
}

[Description("This sample uses SELECTMANY to get all Orders for Customers in Denmark as a flat result as a method query")]
public void LinqToEntities19() {
  _em1.DefaultQueryStrategy = QueryStrategy.DataSourceOnly;
  var query = _em1.Customers.Where(cust => cust.Address.Country == "Denmark")
      .SelectMany(cust => cust.Orders);

  var r = query.ToList();
  Assert.IsTrue(r.Count() == 18);
}


[Description("This sample uses SELECTMANY to get all Orders for Customers in Denmark as a flat result")]
public void LinqToEntities20x() {
  _em1.DefaultQueryStrategy = QueryStrategy.DataSourceOnly;
  var query = from c in _em1.Customers
              where c.Address.Country == "Denmark"
              from o in c.Orders
              where o.Freight > 5
              orderby o.OrderDate
              select o;

  Assert.IsTrue(query.Count() == 17);
  Assert.IsTrue(query.First().OrderDate == new DateTime(1996, 10, 29));
}

[Description("This sample uses SELECTMANY to get all Orders for Customers in Denmark as an anonymous type containing the Orders and Customer flat result")]
public void LinqToEntities21x() {
  _em1.DefaultQueryStrategy = QueryStrategy.Normal.With(QueryInversionMode.Manual);
  var query = from c in _em1.Customers
              where c.Address.Country == "Denmark"
              orderby c.CompanyName
              from o in c.Orders
              where o.Freight > 5
              orderby o.OrderDate
              select new { c, o};

  Assert.IsTrue(query.Count() == 17);
  var x = query.First();
  Assert.IsTrue(query.First().o.OrderDate == new DateTime(1996, 10, 29));
}

[Description("This sample uses SELECTMANY to get all Orders for Customers in Denmark as a flat result using LINQ opeartors")]
public void LinqToEntities22() {
  _em1.DefaultQueryStrategy = QueryStrategy.DataSourceOnly;
  var query = _em1
      .Customers
      .Where(cust => cust.Address.Country == "Denmark")
      .SelectMany(cust => cust.Orders
          .Where(o => o.Freight > 5)
          .OrderBy(o => o.OrderDate));
  var r = query.ToList();
  Assert.IsTrue(r.Count() == 17);
  Assert.IsTrue(r.First().OrderDate == new DateTime(1996, 10, 29));
}

LINQ Examples 5

Include operators-

[Description("Load OrderDetails with Orders ")]
public void LinqToEntities94() {
  var query0 = _em1.Orders.Include("OrderDetails")
      .Where(c => c.Customer.Address.City == "London").Select(o => o);

  var query1 = query0.OrderBy(o => o.OrderID);
  var r1 = query1.ToList();

  var o1 = query1.First();
  var count1 = o1.OrderDetails.Count();
  Assert.IsTrue(count1 == 2);
}

[Description("Load OrderDetails and Products with Orders ")]
public void LinqToEntities95() {
  var query = _em1.Orders
      .Include("OrderDetails")
      .Include("OrderDetails.Product")
      .Take(3).Select(o => o);

  var query2 = query.OrderByDescending(o => o.OrderID);
  var r2 = query2.ToList();
  var p = r2.First().OrderDetails.First().Product;
  Assert.IsNotNull(p);
  Assert.IsFalse(p.EntityAspect.IsNullOrPendingEntity);
}


class MyClass {
 public static decimal Val = 50;

 public decimal GetVal() {
   return MyClass.Val;
  }
}



Closures



[Description("Uses a local variable as a query parameter.")]
public void LinqToEntities91() {
  MyClass c = new MyClass();

  var query = _em1.Orders
      .Where(o => o.Freight > MyClass.Val).Select(o => o);
  Assert.IsTrue(query.Count() == 360);
}

[Description("Uses a the value of the local variable at query execution time.")]
public void LinqToEntities92() {
 decimal x = 50;
  var query = _em1.Orders.Where(o => o.Freight > x).Select(o => new { o.Freight, o });
  Assert.IsTrue(query.Count() == 360);
  x = 100;
  Assert.IsTrue(query.Count() == 187);
}

Friday, 3 January 2014

LINQ Examples 4

Restriction operators- LINQ Where, Any and All operators 

[Description("This sample uses WHERE to find all customers whose contact title is Sales Representative.")]
public void LinqToEntities01() {

  var query = from cust in _em1.Customers
              where cust.ContactTitle == "Sales Representative"
              orderby cust.CompanyName
              select cust;
  var r = query.ToList();
  Assert.IsTrue(r.First().CompanyName == "Alfreds Futterkiste");
}

[Description("This sample uses WHERE to find all orders placed before 1997.")]
public void LinqToEntities02() {
  var metadata = EntityMetadataStore.Instance.GetEntityMetadata(typeof(InternationalOrder));
  DateTime dt = new DateTime(1997, 1, 1);
  var query = from order in _em1.Orders
              where order.OrderDate < dt
              orderby order.OrderDate
              select order;
  Assert.IsTrue(query.First().Freight == 32.38M);
}

[Description("This sample uses WHERE to filter for Products that have stock below their reorder level and have a units on]
public void LinqToEntities03() {
  var query = from p in _em1.Products
              where p.UnitsInStock < p.ReorderLevel && p.UnitsOnOrder == 0
              orderby p.UnitsInStock
              select p;
  Assert.IsTrue(query.First().ProductName == "Nord-Ost Matjeshering");
}

[Description("This sample uses WHERE to filter out Products that have a UnitPrice less than 10.")]
public void LinqToEntities04() {
  var query = from p in _em1.Products
              where p.UnitPrice < 10
              orderby p.ProductName
              select p;
  Assert.IsTrue(query.First().ProductName == "Filo Mix");
}

[Description("This sample uses WHERE to find Employees in London.")]
public void LinqToEntities04a() {
  var query = from e in _em1.Employees
              where e.Address.City == "London"
              orderby e.EmployeeID
              select e;
  Assert.IsTrue(query.First().LastName == "Buchanan");
}

[Description("This sample uses WHERE to get previous employees.")]
public void LinqToEntities05() {
  var query = from e in _em1.Employees
              where e is PreviousEmployee
              orderby e.EmployeeID
              select e;
  var r = query.ToList();
  Assert.IsTrue(r.First().LastName == "King");
}

[Description("This sample uses WHERE to get employees who handle the Boston territory.")]
public void LinqToEntities06() {

  var query = from e in _em1.Employees.OfType<CurrentEmployee>()
              where e.Territories.Any(t => t.TerritoryDescription == "Boston")
              orderby e.EmployeeID
              select e;
  Assert.IsTrue(query.First().LastName == "Fuller");
}

[Description("This sample uses any Customers who placed an order in 1997.")]
public void LinqToEntities07() {
  var query = from c in _em1.Customers
              where c.Orders.Any(o => o.OrderDate.HasValue == true &&
                  o.OrderDate.Value.Year == 1997)
              select c;
  Assert.IsTrue(query.Count() == 85);
}

[Description("This sample uses ANY to check for any out-of-stock products.")]
public void LinqToEntities08() {
  var query = _em1
      .Suppliers
      .Where(s => s.Products
                 .Any(p => p.UnitsInStock == 0))
      .Select(s => s);
  Assert.IsTrue(query.Count() == 5);
}

[Description("This sample uses WHERE and ANY to get orders containing a product with a unit on order.")]
public void LinqToEntities09() {
  var query = from o in _em1.Orders
              where o.OrderDetails.Any(od => od.Product.UnitsOnOrder > 0)
              select o;
  Assert.IsTrue(query.ToList().Count == 366);
  Assert.IsTrue(query.Count() == 366);
}

[Description("This sample uses COUNT to get Products sold to Customers in the same Country " +
    "as the Products' Suppliers, and where all the Products in the order were from the same Country.")]
public void LinqToEntities10() {
  var query = from p in _em1.Products
              where p.OrderDetails.Count(od => od.Order.Customer.Address.Country ==
                  p.Supplier.Address.Country) > 2
              select p;
  Assert.IsTrue(query.Count() == 20);
}


Paging operators- LINQ Take and Skip operators

[Description("This sample uses WHERE to find all customers whose contact title is Sales Representative.")]
public void LinqToEntities96a() {

 // Not a variation of LinqToEntities96, but no numbers were available here.
  var customersQuery = _em1.Customers.OrderBy(c => c.CompanyName);
  customersQuery.QueryStrategy = QueryStrategy.DataSourceOnly;
  ICollection<Customer> customers = customersQuery.Skip(5).Take(5).ToList();
  Assert.IsTrue(customers.Count() == 5);
  customersQuery.QueryStrategy = QueryStrategy.CacheOnly;
  Assert.IsTrue(customersQuery.Count() == 5);
}

[Description("Skip the most recent 2 orders from customers in London")]
public void LinqToEntities96() {
  var query = _em1.Orders
      .Where(o => o.Customer.Address.City == "London")
      .OrderBy(o => o.OrderDate)
      .Skip(2).Select(o => o);

  Assert.IsTrue(query.First().OrderID == 10359);
}

[Description("Take the 2 most recent Orders ")]
public void LinqToEntities97() {
  var query = _em1.Orders
      .OrderBy(o => o.OrderDate)
      .Take(2).Select(o => o);

  Assert.IsTrue(query.Count() == 2);
  Assert.IsTrue(query.First().OrderID == 10248);
}

[Description("Take the 10th to the 20th Orders, ordered by date ")]
public void LinqToEntities98() {
  var query = _em1.Orders
      .OrderBy(o => o.OrderDate)
      .Skip(10).Take(10).Select(o => o);

  query.QueryStrategy = QueryStrategy.DataSourceOnly; // because of skip operator
  var r = query.ToList();
  Assert.IsTrue(r.Count() == 10);
  Assert.IsTrue(r.First().OrderID == 10258);
}

[Description("Use a page number variable to get the xth page")]
public void LinqToEntities99() {
 int pageSize = 10;
 int pageNumber = 4;

  var query = _em1.Orders
      .OrderBy(o => o.OrderDate)
      .Skip(pageSize * pageNumber).Take(pageSize).Select(o => o);
  query.QueryStrategy = QueryStrategy.DataSourceOnly;
  var r = query.ToList();
  Assert.IsTrue(r.Count() == pageSize);
  Assert.IsTrue(r.First().OrderID == 10288);
}


Linq Query to Select Top 5

var list = (from t in ctn.Items           
                 where t.DeliverySelection == true && t.Delivery.SentForDelivery == null           
                 orderby t.Delivery.SubmissionDate select t).Take(5);

Friday, 20 December 2013

LINQ Examples 3

Collection methods id LINQ

Collection methods

Using LINQ, you can modify existing collections, or collections created using other LINQ queries. LINQ provides you a set of functions that can be applied to collections. These functions can be grouped into the following types:
  • Set functions - functions that can be used for collection manipulation operations like merging, intersection, reverse ordering, etc.,
  • Element function - functions that can be used to take particular elements from collections,
  • Conversion functions - functions used to convert a type of collection to another,
  • Aggregation functions - SQL-like functions that enable you to find a maximum, sum, or average value of some field in collections,
  • Quantifier functions - used to quickly traverse through a collection.
These functions are described in the following sections.

Set functions

Set operators enable you to manipulate collections and use standard set operations like unions, intersects, etc. LINQ set operators are:
  • Distinct - used to extract distinct elements from a collection,
  • Union - creates a collection that represents the union of two existing collections,
  • Concat - add elements from one collection to another collection,
  • Intersect - creates a collection that contains elements that exist in both collections,
  • Except - creates a collection that contains elements that exist in one, but do not exist in another collection,
  • Reverse - creates a copy of a collection with elements in reversed order,
  • EquallAll - checks whether two collections have the same elements in the same order,
  • Take - this function takes a number of elements from one collection, and places them in a new collection,
  • Skip - this function skips a number of elements in a collection,
Assuming that the booksByTitle and filteredBooks collection are created in previous examples, the following code finds all books in booksByTitle that do not exist in filteredBooks, and reverses their order.
IEnumerable<Book> otherBooks = booksByTitle.Except(filteredBooks);            

otherBooks = otherBooks.Reverse();  

foreach (Book book in otherBooks)
   Console.WriteLine("Other book - {0} ",  book.Title);
In the following example, booksByTitle and filteredBooks are concatenated and the number of elements and number of distinct elements is shown.
IEnumerable<Book> mergedBooks = booksByTitle.Concat(filteredBooks);
Console.WriteLine("Number of elements in merged collection is {0}", mergedBooks.Count());
Console.WriteLine("Number of distinct elements in merged collection is {0}", mergedBooks.Distinct().Count());

Paging example

In this example is shown an example of client side paging using the Skip(int) and Take(int) methods. Assuming that there are ten books per page, the first three pages are skipped using Skip(30) (ten books per page placed on three pages), and all books that should be shown on the fourth page are taken using Take(10). An example code is:
IEnumerable<Book> page4 = booksByTitle.Skip(30).Take(10);            

foreach (Book book in page4)                
    Console.WriteLine("Fourth page - {0} ", book.Title);
There is also an interesting usage of the Skip/Take functions in the SkipWhile/TakeWhile form:
IEnumerable<Book> page1 = booksByTitle.OrderBy(book=>book.Price)            
                                      .SkipWhile(book=>book.Price<100)
                                      .TakeWhile(book=>book.Price<200);
foreach (Book book in page1)                
    Console.WriteLine("Medium price books - {0} ", book.Title);
In this example, books are ordered by price, all books with price less than 100 are skipped, and all books with price less than 200 are returned. This way all books with price between 100 and 200 are found.

Element functions

There are several useful functions that can be applied when you need to extract a particular element from a collection:
  • First - used to find the first element in a collection. Optionally you can pass a condition to this function in order to find the first element that satisfies the condition.
  • FirstOrDefault - used to find the first element in a collection. If that kind of element cannot be found, the default element for that type (e.g., 0 or null) is returned.
  • ElementAt - used to find the element at a specific position.
The following example shows the usage of the FirstOrDefault and ElementAt functions:
Book firstBook = books.FirstOrDefault(b=>b.Price>200);              
Book thirdBook = books.Where(b=>b.Price>200).ElementAt(2);
Note that you can apply functions either on the collection, or on the result of some other LINQ function.

Conversion functions

There are a few conversion functions that enable you to convert the type of one collection to another. Some of these functions are:
  • ToArray - used to convert elements of collection IEnumerable<T> to array of elements <T>.
  • ToList - used to convert elements of collection IEnumerable<T> to list List<T>.
  • ToDictionary - used to convert elements of a collection to a Dictionary. During conversion, keys and values must be specified.
  • OfType - used to extract the elements of the collection IEnumerable<T1> that implements the interface/class T2, and put them in the collection IEnumerable<T2>.
The following example shows the usage of the ToArray and ToList functions:
Book[] arrBooks = books.ToArray();
List<Book> lstBook = books.ToList();
ToDictionary is an interesting method that enables you to quickly index a list by some field. An example of such a kind of query is shown in the following listing:
Dictionary<string, Book> booksByISBN = books.ToDictionary(book => book.ISBN);
Dictionary<string, double> pricesByISBN = books.ToDictionary(    book => book.ISBN, 
                                book=>book.Price);
If you supply just one lambda expression, ToDictionary will use it as a key of new dictionary while the elements will be the objects. You can also supply lambda expressions for both key and value and create a custom dictionary. In the example above, we create a dictionary of books indexed by the ISBN key, and a dictionary of prices indexed by ISBN.

Quantifier functions

In each collection, you can find a number of logical functions that can be used to quickly travel through a collection and check for some condition. As an example, some of the functions you can use are:
  • Any - checks whether any of the elements in the collection satisfies a certain condition.
  • All - checks whether all elements in the collection satisfies a certain condition.
An example of usage of functions is shown in the following example:
if(list.Any(book=>book.Price<500)) 
    Console.WriteLine("At least one book is cheaper than 500$"); 

if(list.All(book=>book.Price<500))  
    Console.WriteLine("All books are cheaper than 500$");
In the example above, the All and Any functions will check whether the condition that price is less than 500 is satisfied for books in the list.

Aggregation functions

Aggregation functions enable you to perform aggregations on elements of a collection. Aggregation functions that can be used in LINQ are Count, Sum, Min, Max, etc.
The following example shows the simple usage of some aggregate functions applied to an array of integers:
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

Console.WriteLine("Count of numbers greater than 5 is {0} ", numbers.Count( x=>x>5 ));
Console.WriteLine("Sum of even numbers is {0} ", numbers.Sum( x=>(x%2==0) ));
Console.WriteLine("Minimum odd number is {0} ", numbers.Min( x=>(x%2==1) ));
Console.WriteLine("Maximum is {0} ", numbers.Max());
Console.WriteLine("Average is {0} ", numbers.Average());
As you can see, you can use either standard aggregation functions, or you can preselect a subset using a lambda condition.

LINQ Examples 2

LINQ - Using Quantifiers like Any, Contains and All while Querying Objects
Quantifier operations return a Boolean value if some or all of the elements in a sequence satisfy a condition. In this article, we will see some common LINQ to Objects scenarios where we can use these operators.
There are 3 Quantifiers operations that can be used in LINQ:
All – used to determine whether all the elements in a sequence satisfy a condition.
Any - used to determine whether any elements in a sequence satisfy a condition.
Contains - used to determine whether a sequence contains a specified element
 
List<Department> dept = new List<Department>();
    dept.Add(new Department() { DeptID = 1, DeptName = "Marketing", Floor = 1 });
    dept.Add(new Department() { DeptID = 2, DeptName = "Sales", Floor = 2 });
    dept.Add(new Department() { DeptID = 3, DeptName = "Adminis", Floor = 3 });
    dept.Add(new Department() { DeptID = 4, DeptName = "Accounts", Floor = 3 });
    dept.Add(new Department() { DeptID = 5, DeptName = "HR", Floor = 3 });
 
    List<Employee> emp = new List<Employee>();
    emp.Add(new Employee() { EmpID = 1, DeptID = 1, EmpName = "Jack Nolas"});
    emp.Add(new Employee() { EmpID = 2, DeptID = 4, EmpName = "Mark Pine" });
    emp.Add(new Employee() { EmpID = 3, DeptID = 3, EmpName = "Sandra Simte" });
    emp.Add(new Employee() { EmpID = 4, DeptID = 4, EmpName = "Larry Lo"});
    emp.Add(new Employee() { EmpID = 5, DeptID = 3, EmpName = "Sudhir Panj" });
    emp.Add(new Employee() { EmpID = 6, DeptID = 2, EmpName = "Kathy K" });
    emp.Add(new Employee() { EmpID = 7, DeptID = 1, EmpName = "Kaff Joe" });
    emp.Add(new Employee() { EmpID = 8, DeptID = 1, EmpName = "Su Lie" });
 
Using ‘Any’ Quantifier in LINQ
This sample uses the ‘Any’ operator to list down the Departments that do not have Employees
C#
    var noEmp =
        from d in dept
        where !emp.Any(e => e.DeptID == d.DeptID)
        select new { dId = d.DeptID, dNm = d.DeptName };
 
    Console.WriteLine("Departments having no Employees");
    foreach (var empl in noEmp)
    {
        Console.WriteLine("Dept ID - " + empl.dId + ", Dept Name - " + empl.dNm);
 
    }
Output:
Any Operator
 
Using ‘Contains’ Quantifier in LINQ
The following example uses the ‘Contains’ quantifier to find the List of Departments having Employee Names starting with ‘S’
C#
     // Functionality Similar to IN operator
    var hasEmp = dept
         .Where(e => emp.Where(contact =>
         contact.EmpName.StartsWith("S"))
         .Select(d => d.DeptID)
         .Contains(e.DeptID));
 
    Console.WriteLine("/nList of Departments having Employee Names starting with S");
    foreach (var dpt in hasEmp)
    {
        Console.WriteLine("Dept ID - " + dpt.DeptID + ", Dept Name - " + dpt.DeptName);
    }
 
Output:
Contains Operator
Using ‘All’ Quantifier in LINQ
Using the ‘All’ operator, we can determine whether all employees have their names starting with ‘A’
 Console.WriteLine("Find if all Employees have their names starting with 'A'");
 bool chkName = emp.All(e =>
                    e.EmpName.StartsWith("A"));
 Console.WriteLine("Result : " + chkName);
 
 Console.ReadLine();

Output
All Operator