搜索

C# LIST 使用GroupBy分组


发布时间: 2022-11-24 18:09:00    浏览次数:53 次

原有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

免责声明 C# LIST 使用GroupBy分组,资源类别:文本, 浏览次数:53 次, 文件大小:-- , 由本站蜘蛛搜索收录2022-11-24 06:09:00。此页面由程序自动采集,只作交流和学习使用,本站不储存任何资源文件,如有侵权内容请联系我们举报删除, 感谢您对本站的支持。 原文链接:https://www.cnblogs.com/shiyi2014/p/16915602.html