Question

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?

Was it helpful?

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

OTHER TIPS

Sorry for answering twice, but this is legitimately another solution.

You're passing in an Expression<Func<T, DateTime>> but Orderby wants a Func<T, DateTime>

You can either compile the expression:

return new Collection<T>(SortList.OrderBy(OrderByDateTime[0].Compile()).ToList());

or pass in straight out funcs as arguments:

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

I'd recommend reading up on Expressions on msdn

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top