2015-07-21 142 views
1

我正在關注.net中的API構建上的pluralsight課程,而且我似乎遇到了所提供代碼的問題。我有一個類,應該根據提供的查詢參數來對給定的集合進行排序。繼承人的代碼:OrderBy類型的問題無法從使用推斷

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.

回答

3

你似乎是使用動態的LINQ,它允許你使用字符串代替lambda表達式。在這種情況下,您很可能錯過了using語句,因此編譯器正在試圖找出如何將字符串轉換爲lambda。嘗試添加此(注意,這可能不是很正確,因爲我沒有動態LINQ在這裏安裝):

using System.Linq.Dynamic; 
+0

神聖的廢話,它做到了。可能是我應該回家的標誌。 – user4612487

+0

這很奇妙,有時候答案很簡單 - 你只需要有一個清晰的頭:) – DavidG

相關問題