Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

11
  • 26
    To use the '.ElementAt' method, remember: using System.Linq; This is not incluted in fx. auto generated test classes. Commented Nov 24, 2011 at 14:47
  • 17
    This is the way to go if you are modifying the values associated with the keys. Otherwise an exception is thrown when modifying and using foreach(). Commented Apr 3, 2013 at 7:18
  • 48
    Isn't ElementAt a O(n) operation? Commented Feb 7, 2015 at 1:46
  • 211
    This answer is completely undeserving of so many upvotes. A dictionary has no implicit order, so using .ElementAt in this context might lead to subtle bugs. Far more serious is Arturo's point above. You'll be iterating the dictionary dictionary.Count + 1 times leading to O(n^2) complexity for an operation that should only be O(n). If you really need an index (if you do, you're probably using the wrong collection type in the first place), you should iterate dictionary.Select( (kvp, idx) => new {Index = idx, kvp.Key, kvp.Value}) instead and not use .ElementAt inside the loop. Commented Mar 2, 2015 at 2:17
  • 16
    ElementAt - o(n) operation! Seriously? This is the example of how you should not do it. These many upvotes? Commented May 12, 2016 at 22:14