2

一般来说,通用方法对我来说是新的。需要一个返回泛型集合的方法,但也需要一个相同泛型类型的集合并接受

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

范围。整个以下函数的 T 应该是相同的类型,所以我现在使用的是(简化版):

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

但我收到错误:

错误:无法从用法中推断方法“System.Linq.Enumerable.OrderBy(System.Collections.Generic.IEnumberable, System.Func)”的类型参数。尝试明确指定类型参数。

有没有办法做到这一点?

4

2 回答 2

6

很抱歉回答了两次,但这确实是另一种解决方案。

你正在传递一个Expression<Func<T, DateTime>>但 Orderby 想要一个Func<T, DateTime>

您可以编译表达式:

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

或直接传入函数作为参数:

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

我建议阅读msdn 上的表达式

于 2009-09-24T12:22:26.153 回答
4

在这种情况下,编译器无法确定您打算提供给 OrderBy 方法的类型参数,因此您必须显式提供它们:

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

ToList()如果要返回 Collection,您可能需要调用

于 2009-09-24T12:12:10.883 回答