31

出于测试目的,我需要IEnumerable<KeyValuePair<string, string>>使用以下示例键值对创建一个对象:

Key = Name | Value : John
Key = City | Value : NY

最简单的方法是什么?

4

5 回答 5

62

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);
于 2011-01-11T06:28:53.677 回答
8

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

于 2011-01-11T06:29:47.223 回答
5
var List = new List<KeyValuePair<String, String>> { 
  new KeyValuePair<String, String>("Name", "John"), 
  new KeyValuePair<String, String>("City" , "NY")
 };
于 2011-01-11T06:28:14.713 回答
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);
于 2011-01-11T06:32:53.740 回答
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?

于 2011-01-11T06:30:48.430 回答