I have derived a class “ListOfT” from List<T>
to have a place to put function that operate on a list of T.
I have a function that iterates over the list and should return a sub-list of T using Linq:
public class ListOfT : List<T>
{
//no explicit constructor
//other functions to work on this list of T's ...
public ListOfT GenerateSubList()
{
return this.Where(t => t.SomeCriteria).ToList(); // <- compiler will complain
return (ListOfT) this.Where(t => t.SomeCriteria).ToList(); // <- compiler is ok, but I get a runtime error
}
}
The compiler now complains that it can’t cast List<T>
to ListOfT. Obviously the call to “ToList()” will generate a new List<T>
, but I would like to have something that creates an Instance of ListOfT.
I have tried an explicit cast (which will pacify the compiler), but that will lead to a runtime error.
Is there an elegant way to perform this cast (or replace the ToList() call)?
AstaDev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.