rubiktubik
rubiktubik

Reputation: 1001

Creating a Key/Value List with more than one value per key

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

Upvotes: 0

Views: 2122

Answers (3)

vc 74
vc 74

Reputation: 38179

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)
  {
    ...
  }      
}

Upvotes: 2

jaraics
jaraics

Reputation: 4309

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.

Upvotes: 0

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56222

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

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

Upvotes: 2

Related Questions