c# - 使用 lambda 将 Dictionary<Int, Object> 转换为 Dictionary<Int, Object.Property>

标签 c#

假设我有一个具有属性 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/

相关文章:

c# - 如何使用System.CommandLine绑定(bind)NodaTime.Duration?

c# - 更改后 View 不刷新

c# - 拆分字符串和数字并存储在键值对上

c# - 如何在另一个应用程序域中设置静态 bool 值?

c# - ReactiveUI:IObservable.Transform() 不转发通知

c# lambda 表达式 - 将委托(delegate)结果添加到通用列表

c# - 如何修复 IE WebBrowser 控件中的内存泄漏?

c# - 当轮廓可以撕裂时,如何检测简单形状(使用emgu cv)?

c# - 反射 - 获取属性名称

c# - Jqgrid with asp.net [WebMethod] inside aspx page Issue