user4612487
user4612487

Reputation: 287

Issue with OrderBy type cannot be inferred from the usage

I am following a course on pluralsight on API building in .net, and I seem to have run into an issue with the provided code. I have a class that is supposed to sort a given collection based on a provided sting of query params. Heres the code:

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;
    }
}

The problem is with the line:

source = source.OrderBy(completeSortExpression.Remove(completeSortExpression.Count() - 1));

for some reason OrderBy is throwing an error :the type for method OrderBy cannot be inferred from the usage. Try specifying the type arguments explicitly.

Upvotes: 3

Views: 2899

Answers (1)

DavidG
DavidG

Reputation: 119017

You appear to be using dynamic Linq which allows you to use strings in place of lambda expressions. In this case, it's likely you are missing a using statement so the compiler is trying to figure out how to convert the string to a lambda. Try adding this (note that this may not be quite correct as I don't have dynamic linq installed here):

using System.Linq.Dynamic;

Upvotes: 6

Related Questions