Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C# .NET SortedList<T1, T2> actually have ElementAt?

.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 :-\

like image 283
Wayne Werner Avatar asked Dec 01 '22 05:12

Wayne Werner


1 Answers

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).

like image 61
Daniel A.A. Pelsmaeker Avatar answered Dec 05 '22 16:12

Daniel A.A. Pelsmaeker