Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group two lists by index using LINQ

Tags:

c#

linq

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:

  • A
    • Val A, Val A
  • B
    • Val B, Val B
  • C
    • Val C, Val C
  • D
    • Val D

I tried .ToLookup() but I never used that before so I am stuck.

How to achieve this just by using linq.

like image 325
dev hedgehog Avatar asked Oct 26 '25 16:10

dev hedgehog


1 Answers

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.

like image 118
Rawling Avatar answered Oct 29 '25 06:10

Rawling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!