C#
C#

help

Root Question Message

TheHelpfulHelper
TheHelpfulHelper12/12/2022
✅ How do I merge a list of dictionaries based on keys using LINQ?

So if I have something like: [{ number: 1 }, { number: 2 }, { number: 3 }]
I want to get: { number: [1, 2, 3]}

I allow duplicates.
Message Not Public

Sign In and Join Server To See

12/12/2022
TheHelpfulHelper
TheHelpfulHelper12/12/2022
using LINQ
Message Not Public

Sign In and Join Server To See

12/12/2022
Message Not Public

Sign In and Join Server To See

12/12/2022
mtreit
mtreit12/12/2022
Mixing numbers and letters in one dictionary seems odd; what are the TKey and TValue types for your dictionaries? Just string?
TheHelpfulHelper
TheHelpfulHelper12/12/2022
Yeah I just realized that as well, my example wasnt well constructed. I am essentially trying to get the fields of a type using reflection and they all have a type that implements the same interface. So the type of the dictionary is Dictionary<string, IInterface>
TheHelpfulHelper
TheHelpfulHelper12/12/2022
And I need to get the values of multiple of objects of the same type in a single dictionary based on the field name
So the output type is Dictionary<string, List<IInterface>>
Message Not Public

Sign In and Join Server To See

12/12/2022
TheHelpfulHelper
TheHelpfulHelper12/12/2022
Alright I fiddled around and came up with this:
dictionaries
  .SelectMany(dict => dict)
  .ToLookup(pair => pair.Key, pair => pair.Value)
  .ToDictionary(grouping => grouping.Key, grouping => grouping.ToList());

This actually does what I want.
Message Not Public

Sign In and Join Server To See

12/12/2022
Message Not Public

Sign In and Join Server To See

12/12/2022
Message Not Public

Sign In and Join Server To See

12/12/2022
Message Not Public

Sign In and Join Server To See

12/12/2022
mtreit
mtreit12/12/2022
The benchmark results do not favor LINQ here FYI 🙂
mtreit
mtreit12/12/2022
(Of course, when do the benchmark results ever favor LINQ?)
TheHelpfulHelper
TheHelpfulHelper12/13/2022
its manually triggered by UI interaction, so performance is not a concern
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy