- Home /
C# Generic return type
Hey guys,
I want to get the last element in a List. I'm aware you can do List[List-1] but I'm needing to do this a lot and it looks ugly, especially when it is nested:
List<A> list1 = new List<A>();
//A has a data member of type List<B> lets call it list2
//
//add some things to both lists
//
list1[list1.Count-1].list2[List1[list1.Count-1].list2.Count-1].something = somethingElse
Anyway, I want to write a generic method which takes in a list and returns the last element in the List.
I'm aware that List has an extension method, Last(), which does this but I can't work out how to access it, possibly unity does not allow you to do this (http://forum.unity3d.com/threads/70804-C-Extension-Methods)?
I need the return type to be generic but i can't work out how to declare it as such:
public static T /* maybe <T>??*/ getLastListEntry(List<T> list){
return list[list.Count-1];
}
I hope that shows what I am trying to do, hopefully someone can help.
Thanks guys.
Answer by whydoidoit · Aug 10, 2013 at 09:46 PM
Use Linq:
using System.Linq;
var item = someList.Last();
Write it yourself:
public static class ListHelpers
{
public static T LastItem<T>(this List<T> list)
{
return list[list.Count-1];
}
}
var item = someList.LastItem();
Yeah extension methods are cool (don't work in JS but fine in C#) - that could do with a bit of error checking actually:
public static class ListHelpers
{
public static T LastItem<T>(this List<T> list)
{
if(list.Count <=0)
return default(T);
return list[list.Count-1];
}
}
The Linq version will throw an exception if the list is empty - for the same behaviour as my edit above use LastOrDefault()
And here's my article on Linq in Unity: http://unitygems.com/linq-1-time-linq/