Question

 labelMap = new Dictionary<string, int>();
 branchLineMap = new Dictionary<string, int>();

if one key of the first dictionary matches another key of the other dictionary then I need to make a new dictionary with the value of branchlineMap to become the key and the value of LabelMap to become the value. How do I do this while iterating over the whole dictionary?

Était-ce utile?

La solution

Using Where and ToDictionary methods, you can do it like this:

var newDictionary = labelMap
                   .Where(x => branchLineMap.ContainsKey(x.Key))
                   .ToDictionary(x => branchLineMap[x.Key], x => x.Value);

Autres conseils

You could join the two, using LINQ.

Query syntax:

var newDict = (from b in branchLineMap
               join l in labelMap on b.Key equals l.Key
               select new { b = b.Value, l = l.Value })
              .ToDictionary(x => x.b, x => x.l);

Same thing, using method syntax:

var newDict = branchLineMap.Join(labelMap, b => b.Key, l => l.Key,
                                 (b, l) => new { b = b.Value, l = l.Value })
                           .ToDictionary(x => x.b, x => x.l);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top