Skip to content

Instantly share code, notes, and snippets.

@mariusGundersen
Last active October 21, 2018 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mariusGundersen/8b294d95d8f326952c59ed2f42d6d59e to your computer and use it in GitHub Desktop.
Save mariusGundersen/8b294d95d8f326952c59ed2f42d6d59e to your computer and use it in GitHub Desktop.
Duct-typed extension methods Example 7
// 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