0

Let's say I have:

Dictionary<string, List<string>> test = new()
{
    { "animal", ["cat", "dog"] },
    { "fruit", ["banana", "apple"] }
};

I can use:

test.SelectMany(x => x.Value);

to get:

["cat", "dog", "banana", "apple"]

But is it possible to get:

[("animal", "cat"), ("animal", "dog"), ("fruit", "banana"), ("fruit", "apple")]

in a simple, readable way using LINQ dot syntax?

2 Answers 2

4

Use .SelectMany() to flatten the values from the list of tuples which combine from the key and each value.

var result = test.SelectMany(x => x.Value.Select(y => (x.Key, y)))
    .ToList();
1
0

You can use LINQ in the SelectMany itself to map the array value to the needed structure. For example with value tuples:

var valueTuples = test
    .SelectMany(x => x.Value.Select(val => (x.Key, val)))
    .ToList();

This will transform for each value in the array into pair of "current" key and value and flatten the resulting collection.

Not the answer you're looking for? Browse other questions tagged or ask your own question.