Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge group by list in LINQ

Tags:

c#

.net

linq

My List structure is: List<KeyValuePair<string, List<int>>

List of below KeyValue pairs

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)
like image 495
SarkarG Avatar asked Aug 01 '16 10:08

SarkarG


1 Answers

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();

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

like image 107
Gilad Green Avatar answered Nov 19 '22 09:11

Gilad Green