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 ke开发者_如何学Goy value pairs:
Key = Name | Value : John
Key = City | Value : NY
What is the easiest approach to do 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>>
.
var List = new List<KeyValuePair<String, String>> {
new KeyValuePair<String, String>("Name", "John"),
new KeyValuePair<String, String>("City" , "NY")
};
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?
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);
精彩评论