将谓词作为参数传递

时间:2017-02-03 17:58:53

标签: c# sqlite predicate

我试图通过传递谓词作为参数来获得一定数量的元素。但我收到以下错误:

  

无法隐式将System.Collections.Generic.IEnumerable < Students.Entities>类型转换为bool

var names = await Task.Run(() => Repository.GetWithNChildren(e => e.Entities.Take(offset)));


public List<T> GetWithNChildren(Expression<Func<T, bool>> predicate = null)
{
  var db = _factory.GetConnectionWithLock();
  using (db.Lock())
  {
      return db.GetAllWithChildren(predicate, true);
   }
 }

GetAllWithChildren是SQLite类

中的方法
namespace SQLiteNetExtensions.Extensions
{
    public static class ReadOperations
    {
        public static bool EnableRuntimeAssertions;

        public static T FindWithChildren<T>(this SQLiteConnection conn, object pk, bool recursive = false) where T : class;
        public static List<T> GetAllWithChildren<T>(this SQLiteConnection conn, Expression<Func<T, bool>> filter = null, bool recursive = false) where T : class;
        public static void GetChild<T>(this SQLiteConnection conn, T element, string relationshipProperty, bool recursive = false);
        public static void GetChild<T>(this SQLiteConnection conn, T element, Expression<Func<T, object>> propertyExpression, bool recursive = false);
        public static void GetChild<T>(this SQLiteConnection conn, T element, PropertyInfo relationshipProperty, bool recursive = false);
        public static void GetChildren<T>(this SQLiteConnection conn, T element, bool recursive = false);
        public static T GetWithChildren<T>(this SQLiteConnection conn, object pk, bool recursive = false) where T : class;
    }
}

3 个答案:

答案 0 :(得分:1)

Func<T, bool>表示接收T并返回bool的函数。

功能Take(int n)接收IEnumerable<T>并返回最多IEnumerable<T>个成员的n

您需要将e.Entities.Take(offset)更改为返回bool或将Expression<Func<T, bool>> predicate = null切换为Expression<Func<T, U>> predicate = null并将GetAllWithChildren更改为相同类型的内容。

答案 1 :(得分:1)

错误是正确的 这个表达式:

Expression<Func<T, bool>>

表示&#34;我接受一个T的实例,并返回一个布尔值&#34;

但你没有返回booelean:

e => e.Entities.Take(offset)

这是因为 Take(..)不返回布尔值,而是返回IEnumerable of Entities。

要修复它 - 尝试类似:

e => e.Entities.Take(offset).Count() > 3

答案 2 :(得分:-2)

我认为您忘记将您的方法声明为通用。所以,而不是

... GetWithNChildren(Expression<Func<T, bool>> predicate = null)

你应该:

GetWithNChildren<T>(Expression<Func<T, bool>> predicate = null)