无法从使用中推断出 OrderBy 类型的问题

use*_*487 3 c# linq sql-order-by

我正在学习关于在 .net 中构建 API 的pluralsight 课程,我似乎遇到了所提供的代码的问题。我有一个类应该根据提供的查询参数对给定的集合进行排序。代码如下:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

问题在于该行:

source = source.OrderBy(completeSortExpression.Remove(completeSortExpression.Count() - 1));
Run Code Online (Sandbox Code Playgroud)

由于某种原因OrderBy抛出错误:the type for method OrderBy cannot be inferred from the usage. Try specifying the type arguments explicitly.

Dav*_*idG 6

您似乎正在使用动态 Linq,它允许您使用字符串代替 lambda 表达式。在这种情况下,您可能缺少一条using语句,因此编译器会尝试找出如何将字符串转换为 lambda。尝试添加此内容(请注意,这可能不太正确,因为我此处没有安装动态 linq):

using System.Linq.Dynamic;
Run Code Online (Sandbox Code Playgroud)

  • 它适用于我使用 System.Linq.Dynamic.Core; (2认同)