Reputation: 31
Suppose I have a class Building with properties int Id, int Height, int NumberOfFloors.
If I have a Dictionary, where each key is the building 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. Obviously this is feasible with a loop. Just wondering if there is a simple way to do this using 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);
}
Upvotes: 1
Views: 594
Reputation: 273219
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)
.
Upvotes: 5