【问题标题】:Creating the IEnumerable<KeyValuePair<string, string>> Objects with C#?使用 C# 创建 IEnumerable<KeyValuePair<string, string>> 对象?
【发布时间】:2011-06-06 23:45:24
【问题描述】:

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

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

最简单的方法是什么?

【问题讨论】:

  • 您要创建IEnumerable&lt;KeyValuePair&lt;T1,T2&gt;&gt;吗?来自哪个数据源?
  • 初始数据结构没有问题。您可以使用任何数据源。唯一的要求是有一个具有上述键值对的 IEnumerable :)

标签: c# .net ienumerable keyvaluepair


【解决方案1】:
var List = new List<KeyValuePair<String, String>> { 
  new KeyValuePair<String, String>("Name", "John"), 
  new KeyValuePair<String, String>("City" , "NY")
 };

【讨论】:

  • 使用KeyValuePair&lt;string, string&gt;[] 可能比使用List&lt;KeyValuePair&lt;string, string&gt;&gt; 更有效。
【解决方案2】:

任何一个:

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);

【讨论】:

    【解决方案3】:

    Dictionary&lt;string, string&gt; 实现 IEnumerable&lt;KeyValuePair&lt;string,string&gt;&gt;。

    【讨论】:

      【解决方案4】:
      Dictionary<string,string> testDict = new Dictionary<string,string>(2);
      testDict.Add("Name","John");
      testDict.Add("City","NY");
      

      这是你的意思,还是有更多的意思?

      【讨论】:

        【解决方案5】:

        您可以简单地将Dictionary&lt;K, V&gt; 分配给IEnumerable&lt;KeyValuePair&lt;K, V&gt;&gt;

        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);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多