假设我有一个具有属性 int Id、int Height 和 int NumberOfFloors 的 Building 类。
如果我有一个字典,其中每个键都是建筑物 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);
}
最佳答案
它应该是这样的:
var floorDictionary = buildingDictionary
.ToDictionary(kv => kv.Key, kv => kv.Value.NumberofFloors);
源字典实现IEnumerable< KeyValuePair<TKey, TValue> >
为此,有一个扩展方法 ToDictionary(keySelector, valueSelector)
.
关于c# - 使用 lambda 将 Dictionary<Int, Object> 转换为 Dictionary<Int, Object.Property>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33356353/