简体   繁体   English

转换字典 <Int, Object> 到字典 <Int, Object.Property> 与lambdas

[英]Converting Dictionary<Int, Object> To Dictionary<Int, Object.Property> with lambdas

Suppose I have a class Building with properties int Id, int Height, int NumberOfFloors. 假设我有一个带有属性int Id,int Height,int NumberOfFloors的Building类。

If I have a Dictionary, where each key is the building id. 如果我有字典,则每个键都是建筑物ID。 Is there a way to convert this into a Dictionary where each key is the building Id, and each value is the number of floors. 有没有一种方法可以将其转换为Dictionary,其中每个键是建筑物ID,每个值是楼层数。 Obviously this is feasible with a loop. 显然,使用循环是可行的。 Just wondering if there is a simple way to do this using lambdas? 只是想知道是否有使用lambdas进行此操作的简单方法?

Thanks! 谢谢!

var intToBuilding = new Dictionary<int, Building>(); //pretend populated
var intToInt = new Dictionary<int, int>();
foreach(var intBuilding in intToBuilding)
{
  var building = userPreference.Value;
  intToInt.Add(intBuilding.Key, building.Height);
} 

It should go something like: 它应该是这样的:

var floorDictionary = buildingDictionary
   .ToDictionary(kv => kv.Key, kv => kv.Value.NumberofFloors);

The source dictionary implements IEnumerable< KeyValuePair<TKey, TValue> > and for that there is an extension method ToDictionary(keySelector, valueSelector) . 源字典实现IEnumerable< KeyValuePair<TKey, TValue> > ,为此,有一个扩展方法ToDictionary(keySelector, valueSelector)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM