Search code examples
c#genericscollectionsmethodsgeneric-programming

Generic Methods in C#


Generic Methods in general are new to me. Need a method that returns a Collection of a generic type, but also takes a collection of the same generic type and takes

Expression<Func<GenericType, DateTime?>>[] Dates 

parameter. T throughout the following function should be the same type, so right now I was using (simplified version):

private static Collection<T> SortCollection<T>(Collection<T> SortList, Expression<Func<T, DateTime>>[] OrderByDateTime)
{
    return SortList.OrderBy(OrderByDateTime[0]);
}

but i'm receiving error:

Error: The type arguments for method 'System.Linq.Enumerable.OrderBy(System.Collections.Generic.IEnumberable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Is there anyway to do this?


Solution

  • In this situation, the compiler is failing to figure out what type arguments you intend to provide to the OrderBy method, so you'll have to supply them explicitly:

    SortList.OrderBy<T, DateTime>(OrderByDateTime[0])
    

    You'll probably want to call ToList() if you want a Collection to be returned