C# Linq average
Last modified: July 03, 2021class Stock
{
public string Sku { get; set; }
public string ModelName { get; set; }
public string Category { get; set; }
public int Qty { get; set; }
}
class Program
{
static void Main(string[] args)
{
var numbers = new List<int>() { 10, 4, 8,10 };
var fruits = new List<string>() { "Banana", "Apple", "Orange" };
var stock = new List<Stock>()
{
new Stock{Sku = "001", ModelName = "iphone11", Category = "iPhone 11", Qty = 5555 },
new Stock{Sku = "002", ModelName = "iphone11 pro", Category = "iPhone 11", Qty = 44 },
new Stock{Sku = "003", ModelName = "iphone11 pro max", Category = "iPhone 11", Qty = 100 },
new Stock{Sku = "004", ModelName = "iphone12", Category = "iPhone 12", Qty = 55 },
new Stock{Sku = "005", ModelName = "iphone12 pro", Category = "iPhone 12", Qty = 44 },
new Stock{Sku = "006", ModelName = "iphone12 pro max", Category = "iPhone 12", Qty = 10 },
};
var averageNumber = numbers.Average(); //ouput 8
var averageLength = fruits.Average(s => s.Length); //output 5.666666666666667
var averageCategories = (from c in stock
group c by c.Category into d
select (Category: d.Key, AverageStock: d.Average(s => s.Qty))); //ouput iPhone 11:1899.6666666666667, iPhone 12: 36.333333333333336
}
}