Friday, December 28, 2012

LINQ - Aggregate Operators


Introduction

This sample shows different uses of Aggregate Operators:
  • Count - Simple
  • Count - Conditional
  • Count - Nested
  • Count - Grouped
  • Sum - Simple
  • Sum - Projection
  • Sum - Grouped
  • Min - Simple
  • Min - Projection
  • Min - Grouped
  • Min - Elements
  • Max - Simple
  • Max - Projection
  • Max - Grouped
  • Max - Elements
  • Average - Simple
  • Average - Projection
  • Average - Grouped
  • Aggregate - Simple
  • Aggregate - Seed


Description

Count - Simple  

This sample uses Count to get the number of unique factors of 300.
C#
public void Linq73()
{
    int[] factorsOf300 = { 2, 2, 3, 5, 5 };
 
    int uniqueFactors = factorsOf300.Distinct().Count();
 
    Console.WriteLine("There are {0} unique factors of 300.", uniqueFactors);
}
 Result
There are 3 unique factors of 300.

Count - Conditional


This sample uses Count to get the number of odd ints in the array.
C#
public void Linq74()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 
    int oddNumbers = numbers.Count(n => n % 2 == 1);
 
    Console.WriteLine("There are {0} odd numbers in the list.", oddNumbers);
}
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.
C#
public void Linq76()
{
    List<Customer> customers = GetCustomerList();
 
    var orderCounts =
        from c in customers
        select new { c.CustomerID, OrderCount = c.Orders.Count() };
 
    ObjectDumper.Write(orderCounts);
}
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.
C#
public void Linq77()
{
    List<Product> products = GetProductList();
 
    var categoryCounts =
        from p in products
        group p by p.Category into g
        select new { Category = g.Key, ProductCount = g.Count() };
 
    ObjectDumper.Write(categoryCounts
}
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.
C#
public void Linq78()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 
    double numSum = numbers.Sum();
 
    Console.WriteLine("The sum of the numbers is {0}.", numSum);
}
 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.
C#
public void Linq79()
{
    string[] words = { "cherry", "apple", "blueberry" };
 
    double totalChars = words.Sum(w => w.Length);
 
    Console.WriteLine("There are a total of {0} characters in these words.", totalChars);
}
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.
C#
public void Linq80()
{
    List<Product> products = GetProductList();
 
    var categories =
        from p in products
        group p by p.Category into g
        select new { Category = g.Key, TotalUnitsInStock = g.Sum(p => p.UnitsInStock) };
 
    ObjectDumper.Write(categories);
}
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.
C#
public void Linq81()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 
    int minNum = numbers.Min();
 
    Console.WriteLine("The minimum number is {0}.", minNum);
}
Result
The minimum number is 0.

Min - Projection


This sample uses Min to get the length of the shortest word in an array.
C#
public void Linq82()
{
    string[] words = { "cherry", "apple", "blueberry" };
 
    int shortestWord = words.Min(w => w.Length);
 
    Console.WriteLine("The shortest word is {0} characters long.", shortestWord);
}
Result
The shortest word is 5 characters long.

Min - Grouped


This sample uses Min to get the cheapest price among each category's products.
C#
public void Linq83()
{
    List<Product> products = GetProductList();
 
    var categories =
        from p in products
        group p by p.Category into g
        select new { Category = g.Key, CheapestPrice = g.Min(p => p.UnitPrice) };
 
    ObjectDumper.Write(categories);
}
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.
C#
public void Linq84()
{
    List<Product> products = GetProductList();
 
    var categories =
        from p in products
        group p by p.Category into g
        let minPrice = g.Min(p => p.UnitPrice)
        select new { Category = g.Key, CheapestProducts = g.Where(p => p.UnitPrice == minPrice) };
 
    ObjectDumper.Write(categories, 1);
}
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.
C#
public void Linq85()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 
    int maxNum = numbers.Max();
 
    Console.WriteLine("The maximum number is {0}.", maxNum);
}
Result
The maximum number is 9.

Max - Projection


This sample uses Max to get the length of the longest word in an array.
C#
public void Linq86()
{
    string[] words = { "cherry", "apple", "blueberry" };
 
    int longestLength = words.Max(w => w.Length);
 
    Console.WriteLine("The longest word is {0} characters long.", longestLength);
}
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.
C#
public void Linq87()
{
    List<Product> products = GetProductList();
 
    var categories =
        from p in products
        group p by p.Category into g
        select new { Category = g.Key, MostExpensivePrice = g.Max(p => p.UnitPrice) };
 
    ObjectDumper.Write(categories);
}
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.
C#
public void Linq88()
{
    List<Product> products = GetProductList();
 
    var categories =
        from p in products
        group p by p.Category into g
        let maxPrice = g.Max(p => p.UnitPrice)
        select new { Category = g.Key, MostExpensiveProducts = g.Where(p => p.UnitPrice == maxPrice) };
 
    ObjectDumper.Write(categories, 1);
}
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.
C#
public void Linq89()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 
    double averageNum = numbers.Average();
 
    Console.WriteLine("The average number is {0}.", averageNum);
}
Result
The average number is 4.5.

Average - Projection


This sample uses Average to get the average length of the words in the array.
C#
public void Linq90()
{
    string[] words = { "cherry", "apple", "blueberry" };
 
    double averageLength = words.Average(w => w.Length);
 
    Console.WriteLine("The average word length is {0} characters.", averageLength);
}
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.
C#
public void Linq91()
{
    List<Product> products = GetProductList();
 
    var categories =
        from p in products
        group p by p.Category into g
        select new { Category = g.Key, AveragePrice = g.Average(p => p.UnitPrice) };
 
    ObjectDumper.Write(categories);
}

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.
C#
public void Linq92()
{
    double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };
 
    double product = doubles.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);
 
    Console.WriteLine("Total product of all numbers: {0}", product);
}

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.
C#
public void Linq93()
{
    double startBalance = 100.0;
 
    int[] attemptedWithdrawals = { 20, 10, 40, 50, 10, 70, 30 };
 
    double endBalance =
        attemptedWithdrawals.Aggregate(startBalance,
            (balance, nextWithdrawal) =>
                ((nextWithdrawal <= balance) ? (balance - nextWithdrawal) : balance));
 
    Console.WriteLine("Ending balance: {0}", endBalance);
}

Result

Ending balance: 20

No comments:

Post a Comment

Code Formater

Paste Here Your Source Code
Source Code Formatting Options
1) Convert Tab into Space :
2) Need Line Code Numbering :
3) Remove blank lines :
4) Embeded styles / Stylesheet :
5) Code Block Width :
6) Code Block Height :
7) Alternative Background :
Copy Formatted Source Code
 
Preview Of Formatted Code