Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法从用法推断OrderBy类型的问题_C#_Linq_Sql Order By - Fatal编程技术网

C# 无法从用法推断OrderBy类型的问题

C# 无法从用法推断OrderBy类型的问题,c#,linq,sql-order-by,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 (s

我正在学习一门关于在.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;
    }
}

出于某种原因,OrderBy引发了一个错误:无法从用法推断OrderBy方法的类型。尝试显式指定类型参数。

您似乎正在使用动态Linq,它允许您使用字符串代替lambda表达式。在本例中,很可能缺少using语句,因此编译器正试图找出如何将字符串转换为lambda。请尝试添加此注释,这可能不太正确,因为此处未安装动态linq:

using System.Linq.Dynamic;

您似乎正在使用动态Linq,它允许您使用字符串代替lambda表达式。在本例中,很可能缺少using语句,因此编译器正试图找出如何将字符串转换为lambda。请尝试添加此注释,这可能不太正确,因为此处未安装动态linq:

using System.Linq.Dynamic;

天哪,就是这样。也许这是我应该回家的信号。令人惊讶的是,有时候答案非常简单——你只需要有一个清晰的头脑:天哪,就是这样。可能是我该回家的信号。令人惊讶的是,有时候答案非常简单——你只需要有一个清晰的头脑: