Let's suppose I have the following dictionary:
private Dictionary<string, IEnumerable<string>> dic = new Dictionary<string, IEnumerable<string>>();
//.....
dic.Add("abc", new string[] { "1", "2", "3" });
dic.Add("def", new string[] { "-", "!", ")" });
How can I get an IEnumerable<Tuple<string, string>>
containing the following combinations:
{
{ "abc", "1" },
{ "abc", "2" },
{ "abc", "3" },
{ "def", "-" },
{ "def", "!" },
{ "def", ")" }
}
It does not have to be a Tuple<string, string>
, but it seemed to be the more appropiate type.
I was looking for a simple LINQ solution if there is any.
I have tried the following:
var comb = dic.Select(i => i.Value.Select(v => Tuple.Create<string, string>(i.Key, v)));
But comb
ends up being of type IEnumerable<IEnumerable<Tuple<string, string>>>
.
You want Enumerable.SelectMany
which will flatten out your IEnumerable<IEnumerable<T>>
:
var comb = dic.SelectMany(i => i.Value.Select(
v => Tuple.Create(i.Key, v)));
Which yields:
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