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?

有帮助吗?

解决方案

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);

其他提示

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top