List也可以和数据表DataTable 一样按照对象的属性进行分组。

首先先穿件一个实体类 Goods 如下:

   public class Goods
    {
        /// <summary>
        /// 商品编码
        /// </summary>
        public string No { get; set; }

        /// <summary>
        /// 商品名称
        /// </summary>
        public string GoodsName { get; set; }

        /// <summary>
        /// 价格
        /// </summary>
        public decimal Price { get; set; }

        /// <summary>
        /// 类别
        /// </summary>
        public string Category { get; set; }
    }

使用GroupBy对List进行分组代码如下:

static void Main(string[] args)
        {
           //声明一个List集合
            List<Goods> listGoods = new List<Goods>();
            //造一些数据
            for (int i = 0; i < 10; i++)
            {
                if (i < 3)
                {
                    listGoods.Add(new Goods() { No = "100" + i, GoodsName = "商品" + i, Price = 12, Category = "图书" });
                }
                else if (i >= 3 && i < 6)
                {
                    listGoods.Add(new Goods() { No = "100" + i, GoodsName = "商品" + i, Price = 12, Category = "母婴" });
                }
                else
                {
                    listGoods.Add(new Goods() { No = "100" + i, GoodsName = "商品" + i, Price = 12, Category = "手机" });
                }
            }
            //按照类别 Category 分组
            List<IGrouping<string, Goods>> fenzu = listGoods.GroupBy(p => p.Category).ToList();
            foreach (IGrouping<string, Goods> item in fenzu)
            {
                string strGrouping = item.Key;
                Console.WriteLine($"=====小组[{strGrouping}]开始输出=======");
                List<Goods> templist = item.ToList<Goods>();
                foreach (var subitem in templist)
                {
                    Console.WriteLine($"商品编号【{subitem.No}】,商品名称【{subitem.GoodsName}】,商品类别【{subitem.Category}】");
                }
                Console.WriteLine($"=====小组[{strGrouping}]结束输出=======");
            }
            //停留
            Console.ReadLine();
         }

最后执行结果如图

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐