无法从用法推断出 OrderBy 类型的问题
Issue with OrderBy type cannot be inferred from the usage
我正在学习关于 API 在 .net 中构建的 pluralsight 课程,我似乎 运行 遇到了所提供代码的问题。我有一个 class 应该根据提供的查询参数对给定集合进行排序。代码如下:
public static class IQueryableExtensions
{
public static IQueryable<T> ApplySort<T>(this IQueryable<T> source, string sort)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (sort == null)
{
return source;
}
// split the sort string
var lstSort = sort.Split(',');
// run through the sorting options and create a sort expression string from them
string completeSortExpression = "";
foreach (var sortOption in lstSort)
{
// if the sort option starts with "-", we order
// descending, otherwise ascending
if (sortOption.StartsWith("-"))
{
completeSortExpression = completeSortExpression + sortOption.Remove(0, 1) + " descending,";
}
else
{
completeSortExpression = completeSortExpression + sortOption + ",";
}
}
if (!string.IsNullOrWhiteSpace(completeSortExpression))
{
source = source.OrderBy(completeSortExpression.Remove(completeSortExpression.Count() - 1));
}
return source;
}
}
问题在于行:
source = source.OrderBy(completeSortExpression.Remove(completeSortExpression.Count() - 1));
出于某种原因 OrderBy
正在抛出错误:the type for method OrderBy cannot be inferred from the usage. Try specifying the type arguments explicitly.
您似乎在使用动态 Linq,它允许您使用字符串代替 lambda 表达式。在这种情况下,您很可能缺少 using
语句,因此编译器试图弄清楚如何将字符串转换为 lambda。尝试添加这个(注意这可能不太正确,因为我这里没有安装动态 linq):
using System.Linq.Dynamic;
我正在学习关于 API 在 .net 中构建的 pluralsight 课程,我似乎 运行 遇到了所提供代码的问题。我有一个 class 应该根据提供的查询参数对给定集合进行排序。代码如下:
public static class IQueryableExtensions
{
public static IQueryable<T> ApplySort<T>(this IQueryable<T> source, string sort)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (sort == null)
{
return source;
}
// split the sort string
var lstSort = sort.Split(',');
// run through the sorting options and create a sort expression string from them
string completeSortExpression = "";
foreach (var sortOption in lstSort)
{
// if the sort option starts with "-", we order
// descending, otherwise ascending
if (sortOption.StartsWith("-"))
{
completeSortExpression = completeSortExpression + sortOption.Remove(0, 1) + " descending,";
}
else
{
completeSortExpression = completeSortExpression + sortOption + ",";
}
}
if (!string.IsNullOrWhiteSpace(completeSortExpression))
{
source = source.OrderBy(completeSortExpression.Remove(completeSortExpression.Count() - 1));
}
return source;
}
}
问题在于行:
source = source.OrderBy(completeSortExpression.Remove(completeSortExpression.Count() - 1));
出于某种原因 OrderBy
正在抛出错误:the type for method OrderBy cannot be inferred from the usage. Try specifying the type arguments explicitly.
您似乎在使用动态 Linq,它允许您使用字符串代替 lambda 表达式。在这种情况下,您很可能缺少 using
语句,因此编译器试图弄清楚如何将字符串转换为 lambda。尝试添加这个(注意这可能不太正确,因为我这里没有安装动态 linq):
using System.Linq.Dynamic;