C# LIST 使用GroupBy分组

原有list集合

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

List<StoreInfo> storeInfoList = new List<StoreInfo>();
 
    public class StoreInfo
    {
        public string StoreID {get; set;}
        public List<CommodityInfo> List {get; set;}
    }

方案为:

//根据 StoreID分组
                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 个对象

 

//将AllToAddress_List分组取每组的第一条
//多条件分组 .GroupBy(x => new {x.CommodityID, x.CommodityName, x.StoreID}) var resultList = AllToAddress_List.GroupBy(x => new { x.Address, x.Owner_id}).Select(groups => new { FirstOrDefault = groups.FirstOrDefault() });

 

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

posted @ 2022-11-22 16:41  石衣_2014  阅读(4383)  评论(0编辑  收藏  举报