Converting Dictionary<Int, Object> To Dictionary<In

本文关键字:lt Dictionary To In gt Int Converting Object | 更新日期: 2023-09-27 18:19:16

假设我有一个类Building,其属性为int Id, int Height, int NumberOfFloors。

如果我有一个字典,其中每个键是建筑id。是否有一种方法将其转换为字典,其中每个键是建筑Id,每个值是楼层数。显然,这对于循环是可行的。只是想知道是否有一个简单的方法来做到这一点使用lambda ?

谢谢!

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

Converting Dictionary<Int, Object> To Dictionary<In

应该是这样的:

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

源字典实现了IEnumerable< KeyValuePair<TKey, TValue> >,并且有一个扩展方法ToDictionary(keySelector, valueSelector)