C#Linq之求和,平均值,最大值,最小值


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Wolfy.LinqAggregation
{
class Program
{
static void Main(string[] args)
{
//生成測試數據
List<Product> list = new List<Product>();
Random r = new Random();
for (int i = 0; i < 5; i++)
{
float iran = r.Next(1, 111);
Product pro = new Product() {
ID = i + 1,
Name = "寶馬" + i.ToString(),
Price = iran * 1000,
ProductDate = DateTime.Now.AddDays(i) };
Product pro2 = new Product() {
ID = i + 1,
Name = "寶馬" + i.ToString(),
Price = iran * 1000,
ProductDate = DateTime.Now.AddDays(i) };
list.Add(pro);
list.Add(pro2);
}
//求和,求所有的產品總價
var sumResult = from s in list
//根據id分組 將分組后的結果集存入p
group s by s.ID into p
//此時結果集已經是p,所以要從p中取數據。
select new {
key = p.Key,
sum = p.Sum(x => x.Price),
min = p.Min(x => x.Price),
max = p.Max(x => x.Price),
average = p.Average(x => x.Price),
count=p.Count() };
foreach (var item in sumResult)
{
Console.WriteLine("id:" + item.key);
Console.WriteLine("分組的單價總和:" + item.sum);
Console.WriteLine("分組的最小值:"+item.min);
Console.WriteLine("分組的最大值:" + item.max);
Console.WriteLine("分組的平均值:" + item.average);
Console.WriteLine("分組的中個數:" + item.count);
}
Console.Read();
}
}
/// <summary>
/// 產品類
/// </summary>
class Product
{
/// <summary>
/// 產品id
/// </summary>
public int ID { set; get; }
/// <summary>
/// 產品名稱
/// </summary>
public string Name { set; get; }
/// <summary>
/// 產品單價
/// </summary>
public double Price { set; get; }
/// <summary>
/// 生產日期
/// </summary>
public DateTime ProductDate { set; get; }

}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM