Search code examples
c#.netkeyvaluepair

Assigning Values to KeyValuePair


I want to assign some static values to my KeyValuePair object.

private IEnumerable<KeyValuePair<string, string>> getCountries()
{
    return new List<KeyValuePair<string, string>>() 
    { 
      { "code1", "value1" }, 
      { "code2", "value2" } 
    };
}

But this is throwing nooverloaded method error.


Solution

  • return new List<KeyValuePair<string, string>>()
    {
        new KeyValuePair<string, string>("code1", "value1"),
        new KeyValuePair<string, string>("code2", "value2"),
    };
    

    If you're using .NET Core 2.0+, you can use the slightly less verbose:

    return new List<KeyValuePair<string, string>>()
    {
        KeyValuePair.Create("code1", "value1"),
        KeyValuePair.Create("code2", "value2"),
    };
    

    In C# 9, you can use target-typed new to write this as:

    return new List<KeyValuePair<string, string>>()
    {
        new("code1", "value1"),
        new("code2", "value2"),
    };