Dictionary中的一个键和许多不同的值

时间:2013-02-01 04:32:32

标签: c# dictionary

如何在一个键下的 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"));

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

4 个答案:

答案 0 :(得分:3)

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

Dictionary<string,HashSet<DateTime>>

Dictionary<string,List<DateTime>>

答案 1 :(得分:3)

使用Dictionary<string, List<DateTime>>。通过键访问列表,然后将新项添加到列表中。

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

答案 2 :(得分:2)

您可以尝试使用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);

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

答案 3 :(得分:-1)

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

相关问题