0

I understand why there isn't a method built in to do this, however I want a collection object that will allow Value change possibly during Enumeration.

Imagine the following:

Dictionary<string, List<string>> test =  new Dictionary<string, List<string>> {{"key", null}};

Lets say I have 20 of these within a class which implements IEnumberable

I'd like to use lambda or a simple foreach to iterate through the class and find the object matching a key, then store my List<T> with the Value parameter.

Servy
  • 202,030
  • 26
  • 332
  • 449
Ash G
  • 25
  • 3
  • Have you tried using ConcurrentDictionary? – Jon Skeet Oct 31 '12 at 15:52
  • 5
    What's wrong with `if(test.ContainsKey("key"))test["key"] = myList;`? Why do you want to enumerate it? – Tim Schmelter Oct 31 '12 at 15:54
  • 2
    Do you mean 20 dictionary-like objects, or 20 `string`/`List` pairs? If the latter, why do you want to iterate through the pairs rather than access the one you want directly by the key? – Rawling Oct 31 '12 at 15:54
  • Thanks everyone, Tim I didn't think you'd be able to write it like, I was looking for a method of some description :). Time to look at writing the lookup part in lambda! – Ash G Oct 31 '12 at 16:06

4 Answers4

0

You could avoid using an enumerator altogether, e.g.

var data = myEnumerable.ToArray();
for(var i = 0; i < data.Length; i++) {
    // here you can manipulate data[i] to your heart's content
}
Christian Hayter
  • 30,581
  • 6
  • 72
  • 99
0

As you have discovered you can't change a DictionaryEntry through the Value property - you have to go through the Item accessor using the Key.

One option is to turn your Where results to an array then loop to get the matching Keys:

Dictionary<string, List<string>> test =  new Dictionary<string, List<string>>
                                             {{"key", null}};
test.Add("newKey",null);

var matches = test.Where(di => di.Key == "key").ToArray();

foreach(var di in matches) {
    test[di.Key] = new List<string> {"one","two"};
D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

You might be looking for a collection called multimap. See here for my implementation of it.

Community
  • 1
  • 1
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
0

You can just use this to modify a value in a dictionary:

public static void ChangeValue(string indexKey,List<string> newValue)
{
     if (test.ContainsKey(indexKey))
         keysDictionary[indexKey] = newValue;
}
snorifu
  • 49
  • 7