原有list集合,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
List<CommodityInfo> commodityInfoList = new List<CommodityInfo>(); public class CommodityInfo { public string StoreID {get; set;} public string CommodityID {get; set;} public string CommodityName {get; set;} public decimal CommodityPrice {get; set;} } |
如何按照StoreID进行分组,形成如下List
1 2 3 4 5 6 7 8 9 10 11 |
List<StoreInfo> storeInfoList = new List<StoreInfo>(); public class StoreInfo { public string StoreID {get; set;} public List<CommodityInfo> List {get; set;} } |
本来是想循环遍历,然后判断storeId是否存在创建还是添加新对象来着。看到C#有这个GroupBy,干净利落解决了 。方案为:
//根据 StoreID分组
1 2 3 4 5 6 7 8 9 10 11 |
storeInfoList = commodityInfoList.GroupBy(x =>x.StoreID) .Select(group => new StoreInfo { StoreID= group.Key, List= group.ToList() }).ToList(); |
GroupBy 添加分组条件,多个条件时用逗号“,”隔开
.GroupBy(x => new {x.CommodityID, x.CommodityName, x.StoreID})
Select 用于分组之后输出的结果集,可以new 出一个实体,或者直接new 个对象