Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting key-value combinations from a Dictionary using LINQ

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>>>.

like image 715
Matias Cicero Avatar asked Jan 07 '23 23:01

Matias Cicero


1 Answers

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:

enter image description here

like image 180
Yuval Itzchakov Avatar answered Jan 28 '23 20:01

Yuval Itzchakov