使用C#创建IEnumerable <KeyValuePair <string,string >>对象?

Cha*_*ara 27 .net c#

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

Key = Name | Value : John
Key = City | Value : NY
Run Code Online (Sandbox Code Playgroud)

这样做最简单的方法是什么?

Mar*_*ell 55

任何:

values = new Dictionary<string,string> { {"Name", "John"}, {"City", "NY"} };
Run Code Online (Sandbox Code Playgroud)

要么

values = new [] {
      new KeyValuePair<string,string>("Name","John"),
      new KeyValuePair<string,string>("City","NY")
    };
Run Code Online (Sandbox Code Playgroud)

要么:

values = (new[] {
      new {Key = "Name", Value = "John"},
      new {Key = "City", Value = "NY"}
   }).ToDictionary(x => x.Key, x => x.Value);
Run Code Online (Sandbox Code Playgroud)


lep*_*pie 8

Dictionary<string, string>实施IEnumerable<KeyValuePair<string,string>>.


Rob*_*Rob 5

var List = new List<KeyValuePair<String, String>> { 
  new KeyValuePair<String, String>("Name", "John"), 
  new KeyValuePair<String, String>("City" , "NY")
 };
Run Code Online (Sandbox Code Playgroud)

  • 使用`KeyValuePair&lt;string, string&gt;[]` 可能比使用`List&lt;KeyValuePair&lt;string, string&gt;&gt;` 更有效。 (2认同)