如何通过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());
代码说明
- 筛选数据:先用
Where过滤出Categories包含指定cat的元素; - 拆分映射:通过
SelectMany将每个元素和它的每个Group项组合成匿名对象,实现一个元素对应多个分组项的关联; - 分组聚合:以
Group为键,对应的Element为内容进行分组; - 转换字典:用
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
相关产品推荐
相关产品推荐

