32

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?

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
Chathuranga Chandrasekara
  • 20,548
  • 30
  • 97
  • 138

5 Answers5

64

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);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
8

Dictionary<string, string> implements IEnumerable<KeyValuePair<string,string>>.

leppie
  • 115,091
  • 17
  • 196
  • 297
7
var List = new List<KeyValuePair<String, String>> { 
  new KeyValuePair<String, String>("Name", "John"), 
  new KeyValuePair<String, String>("City" , "NY")
 };
Rob
  • 26,989
  • 16
  • 82
  • 98
1
Dictionary<string,string> testDict = new Dictionary<string,string>(2);
testDict.Add("Name","John");
testDict.Add("City","NY");

Is that what you mean, or is there more to it?

leeny
  • 626
  • 3
  • 14
1

You can simply assign a Dictionary<K, V> to IEnumerable<KeyValuePair<K, V>>

IEnumerable<KeyValuePair<string, string>> kvp = new Dictionary<string, string>();

If that does not work you can try -

IDictionary<string, string> dictionary = new Dictionary<string, string>();
            IEnumerable<KeyValuePair<string, string>> kvp = dictionary.Select((pair) => pair);
Unmesh Kondolikar
  • 9,256
  • 4
  • 38
  • 51