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

3
  • possible duplicate of Multi Value Dictionary? Commented Feb 14, 2012 at 7:57
  • Oh Yes, i now use the suggestions for the Multi Value Dictionary Thanks!! Commented Feb 14, 2012 at 8:49
  • possible duplicate of Multi value Dictionary Commented Mar 30, 2013 at 17:41

3 Answers 3

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)
  {
    ...
  }      
}
Sign up to request clarification or add additional context in comments.

1 Comment

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?
2

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

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.