Returning a generic List from a function
As an exercise I'm trying to create a function that returns a generic list from another generic list that's pass开发者_如何学Pythoned to the function. The list passed in could be of either int or string, and I want to return a list of all members of the passed in list that have an even number of characters. The way I'm doing it isn't correct and it doesn't compile, but I want to know why. (I'm using an anonymous method which I know can be replaced with a Lambda expression, but I'd like to know first why it's not working).
List<T> GetEvens(List<T> list)
{
List<T> newList =
list.FindAll(delegate(T t)
{return t.ToString().Length() % 2 == 0;});
return newList;
}
I'm getting an error on lines 3 and 4 saying "The type or namespace name 'T' could not be found". Why doesn't the function recognise 'T'? I know the function will work if I make it a specific return type such as string, but then I'd have to create a separate function for every type I wanted to use which doesn't seem very efficient.
Try List<T> GetEvens<T>( ... )
The reason is that there's no Length method. It's a property so you don't need the parentheses:
return t.ToString().Length % 2 == 0;
But to make you code shorter:
public List<T> GetEvens(List<T> list)
{
return list.FindAll(t => t.ToString().Length % 2 == 0);
}
Length
is a property, not a method, so remove the brackets from it.
精彩评论