【问题标题】:One key and many different values in Dictionary [duplicate]字典中的一个键和许多不同的值[重复]
【发布时间】:2013-01-16 09:07:45
【问题描述】:

如何在Dictionary中存储多个不同的值?

我这里有一个代码:

Dictionary<string, DateTime> SearchDate = new Dictionary<string, DateTime>();

SearchDate.Add("RestDate", Convert.ToDateTime("02/01/2013"));
SearchDate.Add("RestDate", Convert.ToDateTime("02/28/2013"));

但在字典中我了解到只允许使用一个唯一键,所以我的代码产生了错误。

【问题讨论】:

标签: c# dictionary


【解决方案1】:

最简单的方法是制作某种容器的Dictionary,例如

Dictionary<string,HashSet<DateTime>>

Dictionary<string,List<DateTime>>

【讨论】:

    【解决方案2】:

    如果您使用的是 .NET 3.5,则可以使用 Lookup

    【讨论】:

    • 需要注意的一点是 Lookup 是不可变的。一旦创建,您将无法添加更多元素。
    【解决方案3】:

    您可以尝试使用Lookup Class。要创建它,您可以使用Tuple Class:

    var l = new List<Tuple<string,DateTime>>();
    l.Add(new Tuple<string,DateTime>("RestDate", Convert.ToDateTime("02/01/2013")));
    l.Add(new Tuple<string,DateTime>("RestDate", Convert.ToDateTime("02/28/2013")));
    
    var lookup = l.ToLookup(i=>i.Item1);
    

    但是,如果您需要修改查找,则必须修改原始元组列表并从中更新查找。所以,这取决于这个集合的变化频率。

    【讨论】:

      【解决方案4】:

      使用Dictionary&lt;string, List&lt;DateTime&gt;&gt;。按键访问列表,然后将新项目添加到列表中。

      Dictionary<string, List<DateTime>> SearchDate = 
          new Dictionary<string, List<DateTime>>();
      ...
      public void AddItem(string key, DateTime dateItem)
      {
          var listForKey = SearchDate[key];
          if(listForKey == null)
          {
              listForKey = new List<DateTime>();
          }
          listForKey.Add(dateItem);
      }
      

      【讨论】:

        猜你喜欢
        • 2016-10-21
        • 1970-01-01
        • 2011-03-13
        • 2019-04-27
        • 2014-04-05
        • 2020-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多