I need help building a Linq query. I have this dictionary :
var dict = new Dictionary<string, IDictionary<int, double>>
{
{ "one", new Dictionary<int, double>
{
{ 1, 2.0 },
{ 2, 3.0 }
}},
{ "two", new Dictionary<int, double>
{
{ 1, 3.0 },
{ 2, 4.0 },
{ 3, 5.0 }
}},
{ "three", new Dictionary<int, double>
{
{ 1, 4.0 },
{ 2, 5.0}
}}
};
I want to select all “string”/”int” tuples whose associated value is 3.0. With Foreach loops, it looks like :
var res = new Dictionary<string, int>();
foreach (var elem in dict.Select (d => new { S = d.Key, I = d.Value }))
{
foreach (var val in elem.I)
{
if (val.Value == 3.0)
{
res.Add(elem.S, val.Key);
}
}
}
I’m trying to do the same with a single Linq query but with no success (I don’t know how to “join” the key with the value from a subquery). How would you do this?
Thank you in advance!
You could do it this way:
The SelectMany flattens the dictionary of dictionaries into a structure that looks like this:
The Where() limits it down to just the objects with InnerValue = 3.0:
The ToDictionary() looks like this:
If it’s possible for there to be more than a single 3.0 under the same outer key, then you can use ToLookup() instead of ToDictionary().