Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary.ElementAt method is visible in some classes, but not others

Tags:

c#

dictionary

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?

like image 470
sbenderli Avatar asked Feb 12 '10 19:02

sbenderli


People also ask

What is TKey and TValue?

Type ParametersTKey. The type of the keys in the dictionary. TValue. The type of the values in the dictionary. Inheritance.

How dictionary works in c#?

A dictionary, also called an associative array, is a collection of unique keys and a collection of values, where each key is associated with one value. Retrieving and adding values is very fast. Dictionaries take more memory because for each value there is also a key.

What is ElementAt C#?

ElementAt() is a System. Linq method in C# that is used to get and display element at a particular index. The following is our string array − string[] arr = { "One", "Two", "Three", "Four", "Five" }; Now to get an element at index 0, use the ElementAt() method − arr.ElementAt(0); The following is the complete code −


1 Answers

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.

like image 160
dtb Avatar answered Sep 23 '22 15:09

dtb