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?
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.
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.
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).
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.
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);
Dictionary<string, string>
implements IEnumerable<KeyValuePair<string,string>>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With