You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过LINQ实现与手动字典分组一致的列表数据分组

需求描述

我有一个包含多个属性及两个列表的data类,定义如下:

public class data {
    public string Property1 {get; set;}
    public string Property2 {get; set;}
    public List<Enumeration1> Categories {get; set;}
    public List<Enumeration2> Groups {get; set;}
}

需要基于这两个列表过滤数据:已能筛选出Categories列表包含指定项的元素,但需将这些元素按Groups列表中的每个项进行分组——每个元素会被添加到其Groups列表所有项对应的分组中。

目前已实现按Groups列表首个元素分组的LINQ语句:

var groupedElements = from elem in Source.Elements 
  where elem.CategoryList.Contains(cat) 
  group elem by elem.GroupList.FirstOrDefault() into newGroup 
  orderby newGroup.Key 
  select newGroup;

也已通过手动遍历字典的方式实现需求:

var selectedCategory = from elem in Source.Elements where elem.Categories.Contains(cat) select elem;
Dictionary<Enumeration2, List<Element>> groupedElements = new();
foreach (var elem in selectedCategory)
{
    foreach (var group in elem.Groups)
    {
        if (!groupedElements.ContainsKey(group))
            groupedElements.Add(group, new List<Element>());
        groupedElements[group].Add(param);
    }
}

现寻求能达到上述手动字典分组效果的LINQ语句写法。


LINQ实现方案

可以通过SelectMany先将每个元素拆分为其Groups中的每个项与元素本身的配对,再进行分组,最后转换为字典:

var groupedElements = Source.Elements
    .Where(elem => elem.Categories.Contains(cat))
    .SelectMany(elem => elem.Groups.Select(group => new { Group = group, Element = elem }))
    .GroupBy(pair => pair.Group, pair => pair.Element)
    .ToDictionary(g => g.Key, g => g.ToList());

代码说明

  1. 筛选数据:先用Where过滤出Categories包含指定cat的元素;
  2. 拆分映射:通过SelectMany将每个元素和它的每个Group项组合成匿名对象,实现一个元素对应多个分组项的关联;
  3. 分组聚合:以Group为键,对应的Element为内容进行分组;
  4. 转换字典:用ToDictionary将分组结果转为目标格式的字典,和手动遍历的输出完全一致。

如果需要对分组后的键排序,可在GroupBy后添加OrderBy:

var groupedElements = Source.Elements
    .Where(elem => elem.Categories.Contains(cat))
    .SelectMany(elem => elem.Groups.Select(group => new { Group = group, Element = elem }))
    .GroupBy(pair => pair.Group, pair => pair.Element)
    .OrderBy(g => g.Key)
    .ToDictionary(g => g.Key, g => g.ToList());

内容的提问来源于stack exchange,提问作者Daimonion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 21:10:28