14

I have a Dictionary whose elements I need to iterate through and make changes. I cannot use foreach statement, since it sometimes throws InvalidOperationException, saying that the collection cannot be modified during an enumaration.

I can use a for loop, in conjunction with Dictionary.ElementAt method, and I successfully used it in other classes, but in this particular class, the method ElementAt cannot be found! Any ideas?

sbenderli
  • 3,654
  • 9
  • 35
  • 48

1 Answers1

34

ElementAt is an extension method defined in System.Linq.Enumerable.

You need to add a using clause to make it visible:

using System.Linq;

Note that ElementAt on a Dictionary<TKey,TValue> doesn't make a lot of sense, though, as the dictionary implementation does not guarantee elements to be in any specific order, nor that the order does not change if you make changes to the dictionary.

dtb
  • 213,145
  • 36
  • 401
  • 431
  • And make sure your assembly is targeting .NET 3.5 (or higher). – Nate C-K Feb 12 '10 at 19:18
  • Can you provide an example to demonstrate that it is dangerous to rely on the index to access a dictionary? (i.e. where the index changes for a given key). – Dan W May 31 '12 at 00:55
  • Apparently Dictionary doesn't guaranty order. You could get elements in different orders in different iterations through the dictionary. – Tom Cerul Mar 25 '13 at 18:56
  • 1
    This order issue is not merely theoretical. One might be tempted to see that in practice it seems not to change in one's development environment and assume it will never change. But code written this way would break when run in a different environment (slimmed-down/embedded version of .NET, mono, whatever). – Stéphane Gourichon Dec 08 '15 at 09:53
  • Maybe the OrderedDictionary can resolve some of these concerns. – Saturn5 Feb 11 '21 at 11:47