【问题标题】:The type arguments for method Queryable.OrderBy cannot be inferred from the usage无法从用法中推断方法 Queryable.OrderBy 的类型参数
【发布时间】:2019-09-11 05:50:57
【问题描述】:

我正在尝试创建一个通用扩展方法,该方法按特定属性对对象列表进行排序。我的代码出现以下错误。 无法从用法中推断方法 Queryable.OrderBy 的类型参数。尝试明确指定类型参数。

我试图在这里找到答案找不到任何合适的答案。

public static IEnumerable<T> OrderByProperty<T>(this IEnumerable<T> list, 
  string property)
{
  return list.AsQueryable().OrderBy(property);
}

这里有什么我遗漏的吗?

【问题讨论】:

    标签: c# linq extension-methods


    【解决方案1】:

    对我来说,添加以下 using 指令解决了它。

    using System.Linq.Dynamic.Core;
    

    【讨论】:

      【解决方案2】:

      如果你想使用property string name sort data,那么你可以使用System.Linq.DynamicGithub Link

      注意:你必须调用AsQueryable,因为Linq.Dynamic 只支持IQueryable 类型。

      示例:

      void Main()
      {
          var datas = new[] { new { id = 3 }, new { id = 2 } };
          var result = datas.OrderByProperty("id");
          Console.WriteLine(result); //2,3
      }
      
      // Define other methods and classes here
      public static class MyExtension
      {
          public static IEnumerable<T> OrderByProperty<T>(this IEnumerable<T> list,string property)
          {
              return list.AsQueryable().OrderBy(property);
          }
      }
      

      【讨论】:

      • 添加“使用 System.Linq.Dynamic.Core;”为我解决了这个问题。
      【解决方案3】:

      OrderBy 接受 Func&lt;TSource,TKey&gt; 作为参数,而不是 string: Enumerable.OrderBy Method

      我看不出你有任何理由简化足够简单的事情:

      someEnumerable.OrderBy(item => item.Property);
      

      通过string 传递属性也需要反射才能发挥作用,因此非常不鼓励这样做。

      【讨论】:

      • 请注意,对于IQueryable&lt;T&gt;,OP 可能需要Expression&lt;Func&lt;TSource, TKey&gt;&gt; 而不是Func&lt;TSource, TKey&gt;
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多