-1

I want the functionality of a Dictionary, but I want to store multiple values for each key. How can this be done in .NET/C#? Is there any built in collection that supports this scenario?

If I do the following:

collection.Add("key1", new Order(1));
collection.Add("key1", new Order(2));
collection.Add("key1", new Order(3));
collection.Add("key2", new Order(4));

Then running the following should return 3 orders.

collection["key1"];
Erik Z
  • 4,660
  • 6
  • 47
  • 74

5 Answers5

7

Simple: Use Dictionary<string,List<Order>>

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
1

You may use lists for this purpose, if the number of orders per key needs to be variable.

collection.Add("key1"), new List<order>(){new Order(1), new Order(2)});
selkathguy
  • 1,171
  • 7
  • 17
1

I would recommend using a List, Set, or Dictionary as appropriate for your Value in your Dictionary.

For example, you might do:

Dictionary<string, List<string>>
ErikusMaximus
  • 1,150
  • 3
  • 13
  • 28
1

You should think about this in a different way. The Dictionary can hold a list of Orders rather than just a single one, like so:

var collection = Dictionary<string,List<Order>>();

collection.Add("key1", new List<Order>(new { new Order(1), new Order(2),  new Order(3) });
collection.Add("key2", new Order(4));
pingoo
  • 2,074
  • 14
  • 17
0

Try this

    Dictionary<string,order[] order> dict = new Dictionary<string,order[] order>();

    how to access :

    order[] orderArray = dict["key1"];
    order order1 = orderArray[1] ;
    order order2 = orderArray[2] ;

    and goes on...
shujaat siddiqui
  • 1,527
  • 1
  • 20
  • 41