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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With