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.