I would like to group two lists together but only with linq statements. No extra variables or loops.
IEnumerable<string> keys = new List<string>() { "A", "B", "C", "A", "B", "C", "D" };
IEnumerable<string> values = new List<string>() { "Val A", "Val B", "Val C", "Val A", "Val B", "Val C", "Val D" };
Result should be like:
I tried .ToLookup() but I never used that before so I am stuck.
How to achieve this just by using linq.
Another alternative, that isn't O(n^2):
var grouped = keys
.Zip(values, (k, v) => new { k, v })
.GroupBy(kvp => kvp.k)
.ToDictionary(g => g.Key, g => g.Select(kvp => kvp.v));
Note that the dictionary won't preserve the order of the keys; you can use this instead if you'd rather:
var grouped = keys
.Zip(values, (k, v) => new { k, v })
.GroupBy(kvp => kvp.k, kvp => kvp.v);
This will let you iterate through the keys in the order in which they appear in the input, at the expense of not being able to look up via a key.
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