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

Chathuranga Chandrasekara picture Chathuranga Chandrasekara · Jan 11, 2011 · Viewed 41.1k times · Source

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?

Answer

Marc Gravell picture Marc Gravell · Jan 11, 2011

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);