如何在LINQ中按列表合并分组 [英] How to merge group by list in LINQ

查看:284
本文介绍了如何在LINQ中按列表合并分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的列表结构为:List<KeyValuePair<string, List<int>>

键值对下面的列表

Key       Values
[PageA] [1, 3, 4] 
[PageA] [1, 3, 5] 
[PageA] [1, 3, 4, 5, 6]
[PageB] [1, 3, 4, 6] 
[PageC] [1, 3, 4] 
[PageC] [1, 3, 4, 5, 7]

问::如何合并相同键的所有值,还删除重复项,如下所示.

Q: How do i merge all values for the same keys, also removing duplicates as well, like below.

[PageA] [1, 3, 4, 5, 6]
[PageB] [1, 3, 4, 6] 
[PageC] [1, 3, 4, 5, 7]

我试图先将它们分组,然后再将它们分组,但是我无法将它们进一步合并为单个键.

I am trying to group them first, which groups them fine but I am unable to merge those further into single keys.

var pages = pageData.GroupBy(p => p.Key)

推荐答案

Key分组后,应使用SelectMany合并从不同记录中获得的所有集合.这样做之后,您可以调用Distinct.

After grouping by your Key you should use SelectMany to merge all the collection you got from the different records. After doing so you can call Distinct.

var result = pageData.GroupBy(item => item.Key)
                     .Select(group => new 
                     { 
                         Key = group.Key, 
                         Values = group.SelectMany(item => item.Value).Distinct().ToList() 
                     }).ToList();

其他.ToList()都在其中,以便于调试

The additional .ToList()s are just there to ease in debug

这篇关于如何在LINQ中按列表合并分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆