C# LIST 使用GroupBy分组

https://blog.csdn.net/zhangxiao0122/article/details/88570472

根据论坛及博客整理。

原有list集合,

 
  
  1. List commodityInfoList = new List();

  2. public class CommodityInfo

  3. {

  4. public string StoreID {get; set;}

  5. public string CommodityID {get; set;}

  6. public string CommodityName {get; set;}

  7. public decimal CommodityPrice {get; set;}

  8. }

如何按照StoreID进行分组,形成如下List

 
  
  1. List storeInfoList = new List();

  2. public class StoreInfo

  3. {

  4. public string StoreID {get; set;}

  5. public List List {get; set;}

  6. }

方案为:

 
  
  1. //根据 StoreID分组

  2. storeInfoList = commodityInfoList.GroupBy(x =>x.StoreID)

  3. .Select(group => new StoreInfo

  4. {

  5. StoreID= group.Key,

  6. List= group.ToList()

  7. }).ToList();

GroupBy  添加分组条件,多个条件时用逗号“,”隔开

  .GroupBy(x => new {x.CommodityID, x.CommodityName, x.StoreID})

Select 用于分组之后输出的结果集,可以new 出一个实体,或者直接new 个对象

你可能感兴趣的:(.net(C#),泛型(C#),基础知识,c#,list,linq)