Friday, 24 April 2020

C# - LINQ - AggregateOperators



Example 1 - Count() (Unique)
int[] Array = { 2, 2, 3, 5, 5 }; 
int UniqueFactors = Array.Distinct().Count(); 
Console.WriteLine($"There are {UniqueFactors} unique factors."); 
//Output : There are 3 unique factors.

Example 2 - Count() (Conditional- Odd Number)
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);
//Output : There are 5 odd numbers in the list.

Example 3 - Count() (Count On Nested Collection Object )
List<Customer> customers = GetCustomerList();
var orderCounts = from c in customers
                  select (c.CustomerID, OrderCount: 
                                          c.Orders.Count()); 
                                            //Orders[]-Nested Collection

foreach (var customer in orderCounts)
{
    Console.WriteLine($"ID: {customer.CustomerID}, Count:    
                                          {customer.OrderCount}");
}
//Output
//ID: ALFKI, count: 6
//ID: ANATR, count: 4
//ID: ANTON, count: 7
//ID: AROUT, count: 13
//....

Example 4 - Count() (Grouped)
List<Product> products = GetProductList();
var categoryCounts = from p in products
                     group p by p.Category into g
                     select (Category: g.Key, ProductCount: g.Count());
                                       //-g.Key - Get the key of grouping
foreach (var c in categoryCounts)
{
     Console.WriteLine($"Category: {c.Category}
                         Product count: {c.ProductCount}");
}
//Output
//Category: Beverages: Product count: 12
//Category: Condiments: Product count: 12
//Category: Produce: Product count: 5
//Category: Meat / Poultry: Product count: 6
//Category: Seafood: Product count: 12
//Category: Dairy Products: Product count: 10
//Category: Confections: Product count: 13
//Category: Grains / Cereals: Product count: 7


Example 5 - SUM()
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
double numSum = numbers.Sum();
Console.WriteLine($"The sum of the numbers is {numSum}");
//The sum of the numbers is 45

Example 6 - SUM() (Projection)
string[] words = { "cherry""apple""blueberry" };
double totalChars = words.Sum(w => w.Length);
Console.WriteLine($"There are a total of {totalChars} characters in these words.");
//There are a total of 20 characters in these words.

Example 7 - SUM() (Grouped)
List<Product> products = GetProductList();
var categories = from p in products
                 group p by p.Category into g
                 select (Category: g.Key, TotalUnitsInStock:
                                   g.Sum(p => p.UnitsInStock));

foreach (var pair in categories)
{
    Console.WriteLine($"Category: {pair.Category},
                        Units in stock: {pair.TotalUnitsInStock}");
}
//Category: Beverages, Units in stock: 559
//Category: Condiments, Units in stock: 507
//Category: Produce, Units in stock: 100
//Category: Meat / Poultry, Units in stock: 165
//Category: Seafood, Units in stock: 701
//Category: Dairy Products, Units in stock: 393
//Category: Confections, Units in stock: 386
//Category: Grains / Cereals, Units in stock: 308


Example 8 - MIN()
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int minNum = numbers.Min();
Console.WriteLine($"The minimum number is {minNum}");
//The minimum number is 0


Example 9 - MIN() (Projection)     
string[] words = { "cherry""apple""blueberry" };
int shortestWord = words.Min(w => w.Length);
Console.WriteLine($"The shortest word is {shortestWord} characters long.");
// The shortest word is 5 characters long.


Example 10 - MIN() (Grouped)     
List<Product> products = GetProductList();
var categories = from p in products
                 group p by p.Category into g
                 select (Category: g.Key,
                         CheapestPrice: g.Min(p => p.UnitPrice));

foreach (var c in categories)
{
    Console.WriteLine($"Category: {c.Category},
                       Lowest price: {c.CheapestPrice}");
}
//Output
//Category: Beverages, Lowest price: 4.5000
//Category: Condiments, Lowest price: 10.0000
//Category: Produce, Lowest price: 10.0000
//Category: Meat / Poultry, Lowest price: 7.4500
//Category: Seafood, Lowest price: 6.0000
//Category: Dairy Products, Lowest price: 2.5000
//Category: Confections, Lowest price: 9.2000
//Category: Grains / Cereals, Lowest price: 7.0000

Example 11 - MIN() (Grouped Each)     
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 (Category: g.Key,
        CheapestProducts: g.Where(p => p.UnitPrice == minPrice));

foreach (var c in categories)
{
    Console.WriteLine($"Category: {c.Category}");
    foreach (var p in c.CheapestProducts)
    {
        Console.WriteLine($"\tProduct: {p}");
    }
}
//Output
//Category: Beverages
//Product: ProductID = 24 ProductName = Guaraná Fantástica Category = Beverages UnitPrice =$4.50 UnitsInStock = 20
//Category: Condiments
//Product: ProductID = 3 ProductName = Aniseed Syrup Category = Condiments UnitPrice =$10.00 UnitsInStock = 13
//Category: Produce
//Product: ProductID = 74 ProductName = Longlife Tofu Category = Produce UnitPrice =$10.00 UnitsInStock = 4
//Category: Meat / Poultry
//Product: ProductID = 54 ProductName = Tourtière Category = Meat / Poultry UnitPrice =$7.45 UnitsInStock = 21
//Category: Seafood
//Product: ProductID = 13 ProductName = Konbu Category = Seafood UnitPrice =$6.00 UnitsInStock = 24
//Category: Dairy Products
//Product: ProductID = 33 ProductName = Geitost Category = Dairy Products UnitPrice =$2.50 UnitsInStock = 112
//Category: Confections
//Product: ProductID = 19 ProductName = Teatime Chocolate Biscuits Category = Confections UnitPrice =$9.20 UnitsInStock = 25
//Category: Grains / Cereals
//Product: ProductID = 52 ProductName = Filo Mix Category = Grains / Cereals UnitPrice =$7.00 UnitsInStock = 38

Example 12 - MAX()
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int maxNum = numbers.Max();
Console.WriteLine($"The maximum number is {maxNum}");
//The maximum number is 9

Example 13 - MAX() (Projection)
string[] words = { "cherry""apple""blueberry" };
int longestLength = words.Max(w => w.Length);
Console.WriteLine($"The longest word is {longestLength} characters long.");
//The longest word is 9 characters long.

Example 14 - MAX() (Grouped)
List<Product> products = GetProductList();
var categories = from p in products
                 group p by p.Category into g
                 select (Category: g.Key, MostExpensivePrice: g.Max(p => p.UnitPrice));
foreach (var c in categories)
{
       Console.WriteLine($"Category: {c.Category}
                          Most expensive product: {c.MostExpensivePrice}");
}
//Category: Beverages Most expensive product: 263.5000
//Category: Condiments Most expensive product: 43.9000
//Category: Produce Most expensive product: 53.0000
//Category: Meat / Poultry Most expensive product: 123.7900
//Category: Seafood Most expensive product: 62.5000
//Category: Dairy Products Most expensive product: 55.0000
//Category: Confections Most expensive product: 81.0000
//Category: Grains / Cereals Most expensive product: 38.0000

Example 15 - MAX() (Grouped Each)
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 (Category: g.Key,
                         MostExpensiveProducts: g.Where(p => p.UnitPrice == maxPrice));

foreach (var c in categories)
{
       Console.WriteLine($"Category: {c.Category}");
       foreach (var p in c.MostExpensiveProducts)
       {
              Console.WriteLine($"\t{p}");
       }
}
//Category: Beverages
//ProductID = 38 ProductName = Côte de Blaye Category = Beverages UnitPrice =$263.50 UnitsInStock = 17
//Category: Condiments
//ProductID = 63 ProductName = Vegie - spread Category = Condiments UnitPrice =$43.90 UnitsInStock = 24
//Category: Produce
//ProductID = 51 ProductName = Manjimup Dried Apples Category = Produce UnitPrice =$53.00 UnitsInStock = 20
//Category: Meat / Poultry
//ProductID = 29 ProductName = Thüringer Rostbratwurst Category = Meat / Poultry UnitPrice =$123.79 UnitsInStock = 0
//Category: Seafood
//ProductID = 18 ProductName = Carnarvon Tigers Category = Seafood UnitPrice =$62.50 UnitsInStock = 42
//Category: Dairy Products
//ProductID = 59 ProductName = Raclette Courdavault Category = Dairy Products UnitPrice =$55.00 UnitsInStock = 79
//Category: Confections
//ProductID = 20 ProductName = Sir Rodney's Marmalade Category=Confections UnitPrice=$81.00 UnitsInStock=40
//Category: Grains / Cereals
//ProductID = 56 ProductName = Gnocchi di nonna Alice Category = Grains / Cereals UnitPrice =$38.00 UnitsInStock = 21

Example 16 - AVERAGE()
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
double averageNum = numbers.Average();
Console.WriteLine($"The average number is {averageNum}.");
//The average number is 4.5.

Example 17 - AVERAGE() (Projection)
string[] words = { "cherry""apple""blueberry" };
double averageLength = words.Average(w => w.Length);
Console.WriteLine($"The average word length is {averageLength} characters.");
//The average word length is 6.66666666666667 characters.

Example 18 - AVERAGE()(Grouped)
List<Product> products = GetProductList();
var categories = from p in products
      group p by p.Category into g
      select (Category: g.Key,
              AveragePrice: g.Average(p => p.UnitPrice));
 foreach (var c in categories)
 {
     Console.WriteLine($"Category: {c.Category},
                         Average price: {c.AveragePrice}");
 }
 //Category: Beverages, Average price: 37.979166666666666666666666667
 //Category: Condiments, Average price: 23.0625
 //Category: Produce, Average price: 32.3700
 //Category: Meat / Poultry, Average price: 54.006666666666666666666666667
 //Category: Seafood, Average price: 20.6825
 //Category: Dairy Products, Average price: 28.7300
 //Category: Confections, Average price: 25.1600
 //Category: Grains / Cereals, Average price: 20.2500

Example 19 - Aggregate() (Grouped)
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: {product}");


No comments:

Post a Comment