出于测试目的,我需要使用以下示例键值对创建IEnumerable<KeyValuePair<string, string>>
对象:
Key = Name | Value : John
Key = City | Value : NY
最简单的方法是什么?
答案 0 :(得分:53)
任何一个:
values = new Dictionary<string,string> { {"Name", "John"}, {"City", "NY"} };
或
values = new [] {
new KeyValuePair<string,string>("Name","John"),
new KeyValuePair<string,string>("City","NY")
};
或:
values = (new[] {
new {Key = "Name", Value = "John"},
new {Key = "City", Value = "NY"}
}).ToDictionary(x => x.Key, x => x.Value);
答案 1 :(得分:8)
Dictionary<string, string>
实施IEnumerable<KeyValuePair<string,string>>
。
答案 2 :(得分:5)
var List = new List<KeyValuePair<String, String>> {
new KeyValuePair<String, String>("Name", "John"),
new KeyValuePair<String, String>("City" , "NY")
};
答案 3 :(得分:1)
Dictionary<string,string> testDict = new Dictionary<string,string>(2);
testDict.Add("Name","John");
testDict.Add("City","NY");
这是你的意思,还是还有更多呢?
答案 4 :(得分:1)
您只需将Dictionary<K, V>
分配给IEnumerable<KeyValuePair<K, V>>
IEnumerable<KeyValuePair<string, string>> kvp = new Dictionary<string, string>();
如果这不起作用,您可以尝试 -
IDictionary<string, string> dictionary = new Dictionary<string, string>();
IEnumerable<KeyValuePair<string, string>> kvp = dictionary.Select((pair) => pair);