Question

.NET Documentation for 3.5 Collections.Generic.SortedList

In the documentation, it plainly states that "ElementAt" is an extension method on SortedList members. Well, I've got one, declared thusly:

private SortedList<int, ChainLink> linksByLevel = new SortedList<int, ChainLink>();

I try to get the last element:

ChainLink lastLink = linksByLevel.ElementAt(linksByLevel.Count - 1);

The compiler throws the massively helpful message:

Error 1 'System.Collections.Generic.SortedList' does not contain a definition for 'ElementAt' and no extension method 'ElementAt' accepting a first argument of type 'System.Collections.Generic.SortedList<int,ChainLink>' could be found (are you missing a using directive or an assembly reference?)

I'm getting pretty frustrated by the lack of coherence in Microsoft's documentation and my compiler and would love to rant about the inconsistencies between the APIs for SortedList and SortedList<T1, T2>, but I doubt that would add much value to my question. Just trust me, it's frustrating :-\

Was it helpful?

Solution

Try adding an import to the top of your code file:

using System.Linq;

You need to specify that you're using the namespace containing the extension method before you can actually use the extension method. So, as the error explained, you were missing a using-directive.

If you do know that the method is an extension method, but you don't know in which namespace it lives, then you'll probably need to search online to find it. Visual Studio 2012 by default cannot resolve it for you. The extension method you are talking about is Enumerable.ElementAt in the System.Linq namespace of System.Core.dll.

In Visual Studio, when you create a new class file, you'll have using System.Linq inserted at the top automatically. That namespace contains all the LINQ extension methods for working with all kinds of collections (including lists, dictionaries and arrays).

OTHER TIPS

Did you add

using System.Linq;

at the top of your file?

W.R.T. documentation inconsistency, if you look at the SortedList docs, and click through to ElementAt, you'll clearly see at the top of the page that you need to include System.Linq.

SortedList and SortedList<K,V> are very different beasts.

The older SortedList uses an array under the covers and so it can provide an efficient indexer.

Beware that when you use the extension method ElementAt() it will probably do a 'tablescan', don't use it for something time-critical.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top