Search code examples
c#.netienumerablekeyvaluepair

Creating the IEnumerable<KeyValuePair<string, string>> Objects with C#?


For testing purposes, I need to create an IEnumerable<KeyValuePair<string, string>> object with the following sample key value pairs:

Key = Name | Value : John
Key = City | Value : NY

What is the easiest approach to do this?


Solution

  • any of:

    values = new Dictionary<string,string> { {"Name", "John"}, {"City", "NY"} };
    

    or

    values = new [] {
          new KeyValuePair<string,string>("Name","John"),
          new KeyValuePair<string,string>("City","NY")
        };
    

    or:

    values = (new[] {
          new {Key = "Name", Value = "John"},
          new {Key = "City", Value = "NY"}
       }).ToDictionary(x => x.Key, x => x.Value);