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

写在前面

最近一直在弄统计的内容,和统计相关的操作,就需要用到了,而有些在数据库中操作起来非常不方便,没办法就用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

linq入门系列导航

 

原文地址:https://www.cnblogs.com/wolf-sun/p/4483134.html