0

i need a Key/Value List with more than one Value per Key!

What i have tried:

SortedList<string,List<int>> MyList = new SortedList<string,List<int>>();    

But the Problem is that i cannot add values to the List in the SortedList dynamicly?

foreach(var item in MyData)  { MyList.Add(item.Key,item.Value ????); }

How can i solve this problem? Is there allready a list with this features?

Regards rubiktubik

Yahia
  • 69,653
  • 9
  • 115
  • 144
rubiktubik
  • 961
  • 2
  • 12
  • 28
  • possible duplicate of [Multi Value Dictionary?](http://stackoverflow.com/questions/3850930/multi-value-dictionary) – L.B Feb 14 '12 at 07:57
  • Oh Yes, i now use the suggestions for the Multi Value Dictionary Thanks!! – rubiktubik Feb 14 '12 at 08:49
  • possible duplicate of [Multi value Dictionary](http://stackoverflow.com/questions/569903/multi-value-dictionary) – nawfal Mar 30 '13 at 17:41

3 Answers3

2

Look at Lookup(Of TKey, TElement) class, which

Represents a collection of keys each mapped to one or more values.

Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
2

To complement Kirill's valid suggestion of using a Lookup:

var lookup = MyData.ToLookup(item => item.Key);

and then

foreach (var entry in lookup)
{
  string key = entry.Key;
  IEnumerable<int> items = entry;

  foreach (int value in items)
  {
    ...
  }      
}
vc 74
  • 37,131
  • 7
  • 73
  • 89
  • Thank you for your answers! I want to have a List of string as keys and integers as values. I not really understand the usage! How do i create, and add items? – rubiktubik Feb 14 '12 at 08:30
0

Alternatively to the ILookup, you can use a Dictionary<string,List<int>>. When adding/setting an item you should check if there is a list for that Key or not:

Dictionary<string,List<int>> MyList;
void AddItem(string key, int value){
List<int> values;
if(!MyList.TryGet(key, values)){
values= new List<int>();
MyList.Add(key, values);
}
values.Add(value);
}

Iterating through the items is:

foreach (var entry in MyList)
{
string key = entry.Key;
List<int> values = entry.Value;
}

If the values for a key should be unique than instead of a List you can use a HashSet.

jaraics
  • 4,239
  • 3
  • 30
  • 35