Last active
October 21, 2018 12:53
-
-
Save mariusGundersen/8b294d95d8f326952c59ed2f42d6d59e to your computer and use it in GitHub Desktop.
Duct-typed extension methods Example 7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example 7: add a dictionary | |
// These are just some dummy methods for the example to work | |
public static IDictionary<string, int> GetAfricanCountries() => new Dictionary<string, int>{ | |
{ "Nigeria", 190_886_311 }, | |
{ "Ethiopia", 104_957_438 }, | |
{ "Egypt", 97_553_151 } | |
}; | |
public static IDictionary<string, int> GetEuropeanCountries() => new Dictionary<string, int>{ | |
{ "Russia", 146_864_513 }, | |
{ "Germany", 81_914_672 }, | |
{ "United Kingdom", 65_788_574 } | |
}; | |
// This is the dictionary spread method | |
public static void Add<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, IDictionary<TKey, TValue> items) | |
{ | |
foreach (var item in items) | |
{ | |
dictionary[item.Key] = item.Value; | |
} | |
} | |
// It makes this possible | |
var populations = new Dictionary<string, int> | |
{ | |
{ "China", 1_409_517_397 }, | |
{ "India", 1_339_180_127 }, | |
{ "USA", 324_459_463 }, | |
{ "Indonesia", 263_991_379 }, | |
{ "Brazil", 209_288_278 }, | |
GetAfricanCountries(), | |
GetEuropeanCountries() | |
}; | |
// Output each item, to see if things work correctly | |
foreach(var (key, value) in populations) | |
{ | |
Console.WriteLine($"{key}: {value}"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment