Visual studio 2005: List of <T> .First () List <T> .Last () methods in C #?

I used List<T>.First() as well as List<T>.Last() in my VS 2008 C # project, but when I downgraded to 2005, I got these errors:

'System.Collections.Generic.List' does not contain a definition for 'First'

As far as I understand, if there are methods Find () and FindLast () , SHOULD be a very simple way to get iterators to the first and last values, am I right? But I am stuck with this and cannot find anything useful :(

+4
source share
4 answers

First() and Last() are part of LINQ, so they are not found in your VS 2005 project.

If you use List<T> , it is really very easy to find the first and last values ​​if the list is not empty:

 T first = list[0]; T last = list[list.Count-1]; 

If you really need to use iterators, you can easily implement LINQ methods:

 public static T First<T>(IEnumerable<T> source) { foreach (T element in source) { return element; } throw new InvalidOperationException("Empty list"); } public static T Last<T>(IEnumerable<T> source) { T last = default(T); bool gotAny = false; foreach (T element in source) { last = element; gotAny = true; } if (!gotAny) { throw new InvalidOperationException("Empty list"); } return last; } 

(I suspect that the actual implementation of Last checks to see if source IList<T> or not, and returns list[list.Count-1] , if so, to avoid repeating the entire collection.)

As pointed out in the comments, these are not extension methods - you should write:

 // Assuming the method is in a CollectionHelpers class. Foo first = CollectionHelpers.First(list); 

instead

 Foo first = list.First(); 

but the effect is the same.

+11
source

There are 2 problems here.

  • Both the first and the last are extension methods. The compiler included in VS2005 does not support extension methods, so there is no way to bind to them.
  • The first and last methods are included in structure 3.5, which VS2005 cannot use.
+2
source

First not a List<T> method. First is a static method on System.Linq.Enumerable in .net 3.5.

+1
source

These are extension methods. You are raising a typical case against extension methods, whereas they can be confusing because they seem to belong to the class, but are actually completely defined elsewhere. For the first / last for the list, you can still use the list [0] and the list [list.Count-1] (with the addition of error handling, of course).

+1
source

All Articles