views:

963

answers:

2

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?

+3  A: 

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

Rob Fonseca-Ensor
I try that and it says:'System.Collections.ObjectModel.Collection<T>' does not contain a definition for 'OrderBy' and the best extension method overload 'System.Linq.Enumerable.OrderyBy<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>, System.Funct<TSource,TKey>)' has some invalid arguments.
Steph
ok try this: return new Collection<T>(SortList.OrderBy(OrderByDateTime[0].Compile()).ToList());
Rob Fonseca-Ensor
well that's at least not giving me a compiler error, hopefully it will work :-) Thanks!
Steph
+4  A: 

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

Rob Fonseca-Ensor
Will do, I like this solution better anyways I think so I will try this. Thanks again.
Steph
From my point of view this is the more accurate answer too. If you like, you can change the "accepted answer" to this one instead of my other answer to help other people with the same question
Rob Fonseca-Ensor