✅ 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.
11 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
TheHelpfulHelper
TheHelpfulHelperOP2y ago
using LINQ
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
mtreit
mtreit2y ago
Mixing numbers and letters in one dictionary seems odd; what are the TKey and TValue types for your dictionaries? Just string?
TheHelpfulHelper
TheHelpfulHelperOP2y ago
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> 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>>
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
TheHelpfulHelper
TheHelpfulHelperOP2y ago
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());
dictionaries
.SelectMany(dict => dict)
.ToLookup(pair => pair.Key, pair => pair.Value)
.ToDictionary(grouping => grouping.Key, grouping => grouping.ToList());
This actually does what I want.
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
mtreit
mtreit2y ago
The benchmark results do not favor LINQ here FYI 🙂
mtreit
mtreit2y ago
(Of course, when do the benchmark results ever favor LINQ?)
TheHelpfulHelper
TheHelpfulHelperOP2y ago
its manually triggered by UI interaction, so performance is not a concern
Want results from more Discord servers?
Add your server