C#中如何对List集合进行Group by聚合查询呢?


摘要:
下文讲述c#中对List集合执行group by聚合操作的方法分享,如下所示;

group by是一个分组操作,常用于分组统计“***”数据的个数,数据之和,
而List又是c#中常用存储数据的实体,如何对List集合执行group by聚合操作
下文将一一道来,如下所示:

 实现思路:  
     借助linq对List对象执行group by 
      /*
       GroupBy为聚合
       select返回list,并对qty求和
      */
      var q = list
                    .GroupBy(n => new {
                        info = n.info,
                        sort = n.sort
                    }).Select(
                        n => new {
                            info = n.Key.info,
                            sort  = n.Key.sort,
                            qtySum = n.Sum(n2=>n2.qty)
                        }
                      );

例:
List group by示例分享

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;


namespace consoleTest
{ 
    class Program
    {
        static void Main(string[] args)
        { 
            Console.WriteLine("www.maomao365.com cSharp示例分析:");

            //初始化 List集合

            List list = new List();

            list.Add(new infoSinge() { info = "猫猫教程", sort = "A", qty = 88 });
            list.Add(new infoSinge() { info = "猫猫教程", sort = "B", qty = 99 });
            list.Add(new infoSinge() { info = "maomao365.com", sort = "A", qty = 98 });
            list.Add(new infoSinge() { info = "maomao365.com", sort = "A", qty = 87 });
            list.Add(new infoSinge() { info = "maomao365.com", sort = "B", qty = 60 });

            //对list按照info sort分组,并求和qty 

            var q = list
                    .GroupBy(n => new {
                        info = n.info,
                        sort = n.sort
                    }).Select(
                        n => new {
                            info = n.Key.info,
                            sort  = n.Key.sort,
                            qtySum = n.Sum(n2=>n2.qty)
                        }
                      );


            //输出group by 后的测试数据
            if (q.ToList().Count > 0)
            {
                q.ToList().ForEach(t =>
                {
                    Console.WriteLine(t.info + "," + t.sort + "," + t.qtySum);
                });
            }



            Console.ReadLine();
        }


        public   class infoSinge{
              public string info ="";
            public string sort = "";
            public int qty = 0;
        }


    }
}

c#对list进行groupby及求和操作的示例分享

c#对list进行groupby及求和操作的示例分享