寫在前面
最近一直在弄統計的內容,和統計相關的操作,就需要用到了,而有些在數據庫中操作起來非常不方便,沒辦法就用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; } } }
測試結果
總結
在寫group的時候,第一上手就出錯了,很久沒用linq中的group,忘記怎么使用了,竟然還有個into,跟sql語法差別就在這里。這里練習一下,做個備忘。
參考
http://www.cnblogs.com/wuchao/archive/2012/12/25/2832744.html
