Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 971
Chathuranga Chandrasekara Avatar asked Jan 11 '11 06:01

Chathuranga Chandrasekara


People also ask

What is KeyValuePair C#?

The KeyValuePair class stores a pair of values in a single list with C#. Set KeyValuePair and add elements − var myList = new List<KeyValuePair<string, int>>(); // adding elements myList. Add(new KeyValuePair<string, int>("Laptop", 20)); myList.

How do you assign a key-value pair in C#?

To add key-value pair in C# Dictionary, firstly declare a Dictionary. IDictionary<int, string> d = new Dictionary<int, string>(); Now, add elements with KeyValuePair. d.

What is the difference between KeyValuePair and dictionary C#?

KeyValuePair<TKey,TValue> is used in place of DictionaryEntry because it is generified. The advantage of using a KeyValuePair<TKey,TValue> is that we can give the compiler more information about what is in our dictionary. To expand on Chris' example (in which we have two dictionaries containing <string, int> pairs).

Is KeyValuePair serializable C#?

KeyValuePair<> class, but it does not properly serialize in a web service. In a web service, the Key and Value properties are not serialized, making this class useless, unless someone knows a way to fix this.


2 Answers

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); 
like image 179
Marc Gravell Avatar answered Sep 20 '22 09:09

Marc Gravell


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

like image 23
leppie Avatar answered Sep 18 '22 09:09

leppie