1

How can I store many different values in Dictionary under one key?

I have a code here:

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

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

but in Dictionary i learned that only one unique key is allowed, so my code is producing error.

portgas d ace
  • 309
  • 3
  • 9
  • 21
  • 2
    You need a `Dictionary>` – Hans Passant Feb 01 '13 at 04:34
  • This is called a ["Multimap"](http://en.wikipedia.org/wiki/Multimap) and cannot be implemented by the IDictionary contract (although you can do `Dictionary>` or similar manually). If using LINQ, consider using [Lookup](http://msdn.microsoft.com/en-us/library/bb460184.aspx), although it has other implications. –  Feb 01 '13 at 04:34
  • 1
    http://stackoverflow.com/questions/569903/multi-value-dictionary , http://stackoverflow.com/questions/3639972/a-dictionary-with-multiple-entries-with-the-same-key-c-sharp , http://stackoverflow.com/questions/10089850/c-sharp-dictionary-how-to-add-multiple-values-for-single-key , http://stackoverflow.com/questions/2101069/c-sharp-dictionary-one-key-many-values?rq=1 ,etc (-1 because I found these with `[c#] dictionary multiple` and `[c#] dictionary many` - you could have as well!) –  Feb 01 '13 at 04:37

4 Answers4

4

The simplest way is to make a Dictionary of some sort of container, for example

Dictionary<string,HashSet<DateTime>>

or

Dictionary<string,List<DateTime>>
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
4

Use Dictionary<string, List<DateTime>>. Access the list by the key, and then add the new item to the list.

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);
}
Dave Zych
  • 21,581
  • 7
  • 51
  • 66
2

You may try using a Lookup Class. To create it you may use 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);

However, if you need to modify the lookup, you'll have to modify the original list of tuples and update the lookup from it. So, it depends on how often this collection tends to change.

horgh
  • 17,918
  • 22
  • 68
  • 123
-1

You can use Lookup class if you are using .NET 3.5

Iswanto San
  • 18,263
  • 13
  • 58
  • 79