101 LINQ Samples: Aggregator Operators

Count - Simple

This sample uses Count to get the number of unique factors of 300.

  1. public void Linq73()
  2. {
  3.     int[] factorsOf300 = { 22355 };
  4.  
  5.     int uniqueFactors = factorsOf300.Distinct().Count();
  6.  
  7.     Console.WriteLine("There are {0} unique factors of 300.", uniqueFactors);
  8. }

Result

There are 3 unique factors of 300.

Count - Conditional

This sample uses Count to get the number of odd ints in the array.

  1. public void Linq74()
  2. {
  3.     int[] numbers = { 5413986720 };
  4.  
  5.     int oddNumbers = numbers.Count(n => n % 2 == 1);
  6.  
  7.     Console.WriteLine("There are {0} odd numbers in the list.", oddNumbers);
  8. }

Result

There are 5 odd numbers in the list.

Count - Nested

This sample uses Count to return a list of customers and how many orders each has.

  1. public void Linq76()
  2. {
  3.     List<Customer> customers = GetCustomerList();
  4.  
  5.     var orderCounts =
  6.         from c in customers
  7.         select new { c.CustomerID, OrderCount = c.Orders.Count() };
  8.  
  9.     ObjectDumper.Write(orderCounts);
  10. }

Result

CustomerID=ALFKI 
CustomerID=ANATR 
CustomerID=ANTON 
CustomerID=AROUT 
CustomerID=BERGS 
CustomerID=BLAUS 
CustomerID=BLONP 
CustomerID=BOLID 
CustomerID=BONAP 
CustomerID=BOTTM 
CustomerID=BSBEV 
CustomerID=CACTU 
CustomerID=CENTC 
CustomerID=CHOPS 
CustomerID=COMMI 
CustomerID=CONSH 
CustomerID=DRACD 
CustomerID=DUMON 
CustomerID=EASTC 
CustomerID=ERNSH 
CustomerID=FAMIA 
CustomerID=FISSA 
CustomerID=FOLIG 
CustomerID=FOLKO 
CustomerID=FRANK 
CustomerID=FRANR 
CustomerID=FRANS 
CustomerID=FURIB 
CustomerID=GALED 
CustomerID=GODOS 
CustomerID=GOURL 
CustomerID=GREAL 
CustomerID=GROSR 
CustomerID=HANAR 
CustomerID=HILAA 
CustomerID=HUNGC 
CustomerID=HUNGO 
CustomerID=ISLAT 
CustomerID=KOENE 
CustomerID=LACOR 
CustomerID=LAMAI 
CustomerID=LAUGB 
CustomerID=LAZYK 
CustomerID=LEHMS 
CustomerID=LETSS 
CustomerID=LILAS 
CustomerID=LINOD 
CustomerID=LONEP 
CustomerID=MAGAA 
CustomerID=MAISD 
CustomerID=MEREP 
CustomerID=MORGK 
CustomerID=NORTS 
CustomerID=OCEAN 
CustomerID=OLDWO 
CustomerID=OTTIK 
CustomerID=PARIS 
CustomerID=PERIC 
CustomerID=PICCO 
CustomerID=PRINI 
CustomerID=QUEDE 
CustomerID=QUEEN 
CustomerID=QUICK 
CustomerID=RANCH 
CustomerID=RATTC 
CustomerID=REGGC 
CustomerID=RICAR 
CustomerID=RICSU 
CustomerID=ROMEY 
CustomerID=SANTG 
CustomerID=SAVEA 
CustomerID=SEVES 
CustomerID=SIMOB 
CustomerID=SPECD 
CustomerID=SPLIR 
CustomerID=SUPRD 
CustomerID=THEBI 
CustomerID=THECR 
CustomerID=TOMSP 
CustomerID=TORTU 
CustomerID=TRADH 
CustomerID=TRAIH 
CustomerID=VAFFE 
CustomerID=VICTE 
CustomerID=VINET 
CustomerID=WANDK 
CustomerID=WARTH 
CustomerID=WELLI 
CustomerID=WHITC 
CustomerID=WILMK 
CustomerID=WOLZA
OrderCount=6 
OrderCount=4 
OrderCount=7 
OrderCount=13 
OrderCount=18 
OrderCount=7 
OrderCount=11 
OrderCount=3 
OrderCount=17 
OrderCount=14 
OrderCount=10 
OrderCount=6 
OrderCount=1 
OrderCount=8 
OrderCount=5 
OrderCount=3 
OrderCount=6 
OrderCount=4 
OrderCount=8 
OrderCount=30 
OrderCount=7 
OrderCount=0 
OrderCount=5 
OrderCount=19 
OrderCount=15 
OrderCount=3 
OrderCount=6 
OrderCount=8 
OrderCount=5 
OrderCount=10 
OrderCount=9 
OrderCount=11 
OrderCount=2 
OrderCount=14 
OrderCount=18 
OrderCount=5 
OrderCount=19 
OrderCount=10 
OrderCount=14 
OrderCount=4 
OrderCount=14 
OrderCount=3 
OrderCount=2 
OrderCount=15 
OrderCount=4 
OrderCount=14 
OrderCount=12 
OrderCount=8 
OrderCount=10 
OrderCount=7 
OrderCount=13 
OrderCount=5 
OrderCount=3 
OrderCount=5 
OrderCount=10 
OrderCount=9 
OrderCount=0 
OrderCount=6 
OrderCount=10 
OrderCount=6 
OrderCount=9 
OrderCount=13 
OrderCount=28 
OrderCount=5 
OrderCount=18 
OrderCount=12 
OrderCount=11 
OrderCount=10 
OrderCount=5 
OrderCount=6 
OrderCount=31 
OrderCount=9 
OrderCount=7 
OrderCount=4 
OrderCount=9 
OrderCount=12 
OrderCount=4 
OrderCount=3 
OrderCount=5 
OrderCount=10 
OrderCount=7 
OrderCount=3 
OrderCount=11 
OrderCount=10 
OrderCount=4 
OrderCount=10 
OrderCount=15 
OrderCount=9 
OrderCount=14 
OrderCount=8 
OrderCount=7


Count - Grouped

This sample uses Count to return a list of categories and how many products each has.

  1. public void Linq77()
  2. {
  3.     List<Product> products = GetProductList();
  4.  
  5.     var categoryCounts =
  6.         from p in products
  7.         group p by p.Category into g
  8.         select new { Category = g.Key, ProductCount = g.Count() };
  9.  
  10.     ObjectDumper.Write(categoryCounts
  11. }

Result

Category=Beverages 
Category=Condiments 
Category=Produce 
Category=Meat/Poultry 
Category=Seafood 
Category=Dairy Products 
Category=Confections 
Category=Grains/Cereals
ProductCount=12 
ProductCount=12 
ProductCount=5 
ProductCount=6 
ProductCount=12 
ProductCount=10 
ProductCount=13 
ProductCount=7


Sum - Simple

This sample uses Sum to get the total of the numbers in an array.

  1. public void Linq78()
  2. {
  3.     int[] numbers = { 5413986720 };
  4.  
  5.     double numSum = numbers.Sum();
  6.  
  7.     Console.WriteLine("The sum of the numbers is {0}.", numSum);
  8. }

Result

The sum of the numbers is 45.

Sum - Projection

This sample uses Sum to get the total number of characters of all words in the array.

  1. public void Linq79()
  2. {
  3.     string[] words = { "cherry""apple""blueberry" };
  4.  
  5.     double totalChars = words.Sum(w => w.Length);
  6.  
  7.     Console.WriteLine("There are a total of {0} characters in these words.", totalChars);
  8. }

Result

There are a total of 20 characters in these words.

Sum - Grouped

This sample uses Sum to get the total units in stock for each product category.

  1. public void Linq80()
  2. {
  3.     List<Product> products = GetProductList();
  4.  
  5.     var categories =
  6.         from p in products
  7.         group p by p.Category into g
  8.         select new { Category = g.Key, TotalUnitsInStock = g.Sum(p => p.UnitsInStock) };
  9.  
  10.     ObjectDumper.Write(categories);
  11. }

Result

Category=Beverages 
Category=Condiments 
Category=Produce 
Category=Meat/Poultry 
Category=Seafood 
Category=Dairy Products 
Category=Confections 
Category=Grains/Cereals
TotalUnitsInStock=559 
TotalUnitsInStock=507 
TotalUnitsInStock=100 
TotalUnitsInStock=165 
TotalUnitsInStock=701 
TotalUnitsInStock=393 
TotalUnitsInStock=386 
TotalUnitsInStock=308


Min - Simple

This sample uses Min to get the lowest number in an array.

  1. public void Linq81()
  2. {
  3.     int[] numbers = { 5413986720 };
  4.  
  5.     int minNum = numbers.Min();
  6.  
  7.     Console.WriteLine("The minimum number is {0}.", minNum);
  8. }

Result

The minimum number is 0.

Min - Projection

This sample uses Min to get the length of the shortest word in an array.

  1. public void Linq82()
  2. {
  3.     string[] words = { "cherry""apple""blueberry" };
  4.  
  5.     int shortestWord = words.Min(w => w.Length);
  6.  
  7.     Console.WriteLine("The shortest word is {0} characters long.", shortestWord);
  8. }

Result

The shortest word is 5 characters long.

Min - Grouped

This sample uses Min to get the cheapest price among each category's products.

  1. public void Linq83()
  2. {
  3.     List<Product> products = GetProductList();
  4.  
  5.     var categories =
  6.         from p in products
  7.         group p by p.Category into g
  8.         select new { Category = g.Key, CheapestPrice = g.Min(p => p.UnitPrice) };
  9.  
  10.     ObjectDumper.Write(categories);
  11. }

Result

Category=Beverages
Category=Condiments
Category=Produce
Category=Meat/Poultry
Category=Seafood
Category=Dairy Products
Category=Confections
Category=Grains/Cereals
CheapestPrice=4.5000
CheapestPrice=10.0000
CheapestPrice=10.0000
CheapestPrice=7.4500
CheapestPrice=6.0000
CheapestPrice=2.5000
CheapestPrice=9.2000
CheapestPrice=7.0000


Min - Elements

This sample uses Min to get the products with the cheapest price in each category.

  1. public void Linq84()
  2. {
  3.     List<Product> products = GetProductList();
  4.  
  5.     var categories =
  6.         from p in products
  7.         group p by p.Category into g
  8.         let minPrice = g.Min(p => p.UnitPrice)
  9.         select new { Category = g.Key, CheapestProducts = g.Where(p => p.UnitPrice == minPrice) };
  10.  
  11.     ObjectDumper.Write(categories, 1);
  12. }

Result

Category=Beverages      CheapestProducts=... 
  CheapestProducts: ProductID=24  ProductName=Guaraná Fantástica  Category=Beverages      UnitPrice=4.5000        UnitsInStock=20 
Category=Condiments    CheapestProducts=... 
  CheapestProducts: ProductID=3  ProductName=Aniseed Syrup      Category=Condiments    UnitPrice=10.0000      UnitsInStock=13 
Category=Produce        CheapestProducts=... 
  CheapestProducts: ProductID=74  ProductName=Longlife Tofu      Category=Produce        UnitPrice=10.0000      UnitsInStock=4 
Category=Meat/Poultry  CheapestProducts=... 
  CheapestProducts: ProductID=54  ProductName=Tourtière  Category=Meat/Poultry  UnitPrice=7.4500        UnitsInStock=21 
Category=Seafood        CheapestProducts=... 
  CheapestProducts: ProductID=13  ProductName=Konbu      Category=Seafood        UnitPrice=6.0000        UnitsInStock=24 
Category=Dairy Products        CheapestProducts=... 
  CheapestProducts: ProductID=33  ProductName=Geitost    Category=Dairy Products        UnitPrice=2.5000        UnitsInStock=112 
Category=Confections    CheapestProducts=... 
  CheapestProducts: ProductID=19  ProductName=Teatime Chocolate Biscuits  Category=Confections    UnitPrice=9.2000        UnitsInStock=25 
Category=Grains/Cereals        CheapestProducts=... 
  CheapestProducts: ProductID=52  ProductName=Filo Mix    Category=Grains/Cereals        UnitPrice=7.0000        UnitsInStock=38

Max - Simple

This sample uses Max to get the highest number in an array.

  1. public void Linq85()
  2. {
  3.     int[] numbers = { 5413986720 };
  4.  
  5.     int maxNum = numbers.Max();
  6.  
  7.     Console.WriteLine("The maximum number is {0}.", maxNum);
  8. }

Result

The maximum number is 9.

Max - Projection

This sample uses Max to get the length of the longest word in an array.

  1. public void Linq86()
  2. {
  3.     string[] words = { "cherry""apple""blueberry" };
  4.  
  5.     int longestLength = words.Max(w => w.Length);
  6.  
  7.     Console.WriteLine("The longest word is {0} characters long.", longestLength);
  8. }

Result

The longest word is 9 characters long.

Max - Grouped

This sample uses Max to get the most expensive price among each category's products.

  1. public void Linq87()
  2. {
  3.     List<Product> products = GetProductList();
  4.  
  5.     var categories =
  6.         from p in products
  7.         group p by p.Category into g
  8.         select new { Category = g.Key, MostExpensivePrice = g.Max(p => p.UnitPrice) };
  9.  
  10.     ObjectDumper.Write(categories);
  11. }

Result

Category=Beverages 
Category=Condiments 
Category=Produce 
Category=Meat/Poultry 
Category=Seafood 
Category=Dairy Products 
Category=Confections 
Category=Grains/Cereals
MostExpensivePrice=263.5000 
MostExpensivePrice=43.9000 
MostExpensivePrice=53.0000 
MostExpensivePrice=123.7900 
MostExpensivePrice=62.5000 
MostExpensivePrice=55.0000 
MostExpensivePrice=81.0000 
MostExpensivePrice=38.0000


Max - Elements

This sample uses Max to get the products with the most expensive price in each category.

  1. public void Linq88()
  2. {
  3.     List<Product> products = GetProductList();
  4.  
  5.     var categories =
  6.         from p in products
  7.         group p by p.Category into g
  8.         let maxPrice = g.Max(p => p.UnitPrice)
  9.         select new { Category = g.Key, MostExpensiveProducts = g.Where(p => p.UnitPrice == maxPrice) };
  10.  
  11.     ObjectDumper.Write(categories, 1);
  12. }

Result

Category=Beverages      MostExpensiveProducts=... 
  MostExpensiveProducts: ProductID=38    ProductName=Côte de Blaye      Category=Beverages      UnitPrice=263.5000      UnitsInStock=17 
Category=Condiments    MostExpensiveProducts=... 
  MostExpensiveProducts: ProductID=63    ProductName=Vegie-spread        Category=Condiments    UnitPrice=43.9000      UnitsInStock=24 
Category=Produce        MostExpensiveProducts=... 
  MostExpensiveProducts: ProductID=51    ProductName=Manjimup Dried Apples      Category=Produce        UnitPrice=53.0000      UnitsInStock=20 
Category=Meat/Poultry  MostExpensiveProducts=... 
  MostExpensiveProducts: ProductID=29    ProductName=Thüringer Rostbratwurst    Category=Meat/Poultry  UnitPrice=123.7900      UnitsInStock=0 
Category=Seafood        MostExpensiveProducts=... 
  MostExpensiveProducts: ProductID=18    ProductName=Carnarvon Tigers    Category=Seafood        UnitPrice=62.5000      UnitsInStock=42 
Category=Dairy Products        MostExpensiveProducts=... 
  MostExpensiveProducts: ProductID=59    ProductName=Raclette Courdavault        Category=Dairy Products        UnitPrice=55.0000      UnitsInStock=79 
Category=Confections    MostExpensiveProducts=... 
  MostExpensiveProducts: ProductID=20    ProductName=Sir Rodney's Marmalade      Category=Confections    UnitPrice=81.0000      UnitsInStock=40 
Category=Grains/Cereals        MostExpensiveProducts=... 
  MostExpensiveProducts: ProductID=56    ProductName=Gnocchi di nonna Alice      Category=Grains/Cereals        UnitPrice=38.0000      UnitsInStock=21

Average - Simple

This sample uses Average to get the average of all numbers in an array.

  1. public void Linq89()
  2. {
  3.     int[] numbers = { 5413986720 };
  4.  
  5.     double averageNum = numbers.Average();
  6.  
  7.     Console.WriteLine("The average number is {0}.", averageNum);
  8. }

Result

The average number is 4.5.

Average - Projection

This sample uses Average to get the average length of the words in the array.

  1. public void Linq90()
  2. {
  3.     string[] words = { "cherry""apple""blueberry" };
  4.  
  5.     double averageLength = words.Average(w => w.Length);
  6.  
  7.     Console.WriteLine("The average word length is {0} characters.", averageLength);
  8. }

Result

The average word length is 6.66666666666667 characters.

Average - Grouped

This sample uses Average to get the average price of each category's products.

  1. public void Linq91()
  2. {
  3.     List<Product> products = GetProductList();
  4.  
  5.     var categories =
  6.         from p in products
  7.         group p by p.Category into g
  8.         select new { Category = g.Key, AveragePrice = g.Average(p => p.UnitPrice) };
  9.  
  10.     ObjectDumper.Write(categories);
  11. }

Result

Category=Beverages 
Category=Condiments 
Category=Produce 
Category=Meat/Poultry 
Category=Seafood 
Category=Dairy Products 
Category=Confections 
Category=Grains/Cereals
AveragePrice=37.979166666666666666666666667 
AveragePrice=23.0625 
AveragePrice=32.3700 
AveragePrice=54.006666666666666666666666667 
AveragePrice=20.6825 
AveragePrice=28.7300 
AveragePrice=25.1600 
AveragePrice=20.2500


Aggregate - Simple

This sample uses Aggregate to create a running product on the array that calculates the total product of all elements.

  1. public void Linq92()
  2. {
  3.     double[] doubles = { 1.72.31.94.12.9 };
  4.  
  5.     double product = doubles.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);
  6.  
  7.     Console.WriteLine("Total product of all numbers: {0}", product);
  8. }

Result

Total product of all numbers: 88.33081

Aggregate - Seed

This sample uses Aggregate to create a running account balance that subtracts each withdrawal from the initial balance of 100, as long as the balance never drops below 0

  1. public void Linq93()
  2. {
  3.     double startBalance = 100.0;
  4.  
  5.     int[] attemptedWithdrawals = { 20104050107030 };
  6.  
  7.     double endBalance =
  8.         attemptedWithdrawals.Aggregate(startBalance,
  9.             (balance, nextWithdrawal) =>
  10.                 ((nextWithdrawal <= balance) ? (balance - nextWithdrawal) : balance));
  11.  
  12.     Console.WriteLine("Ending balance: {0}", endBalance);
  13. }

Result

Ending balance: 20

posted @ 2011-03-13 20:19  i'm zjz  阅读(297)  评论(0编辑  收藏  举报