Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual studio 2005: List<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've downgraded to 2005 I got errors like this:

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

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

like image 683
Nik Avatar asked Dec 07 '22 07:12

Nik


1 Answers

First() and Last() are part of LINQ which is why they're not being found in your VS 2005 project.

If you're using a List<T> it's really, really easy to find the first and last values, assuming the list is non-empty:

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

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

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 the real implementation of Last checks whether source is an IList<T> or not and returns list[list.Count-1] if so, to avoid having to iterate through the whole collection.)

As pointed out in the comments, these aren't extension methods - you'd write:

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

instead of

Foo first = list.First();

but the effect is the same.

like image 137
Jon Skeet Avatar answered Dec 28 '22 23:12

Jon Skeet