无法将lambda表达式转换为委托类型

时间:2016-01-11 12:39:58

标签: c# lambda delegates

我有这样的方法:

public ICollection<T> GetEntitiesWithPredicate(Expression<Func<T, bool>> predicate)
{
           // ...
}

我在另一个类中执行方法调用,如

service.GetEntitiesWithPredicate(x => x.FoobarCollection.Where(y => y.Text.Contains(SearchText)));

但我总是得到这个错误:

Lambda expression cannot be converted to '<typename>' because '<typename>' is not a delegate type

我需要做些什么来改变这项工作?

编辑:

我使用Entity Framework 6,如果我使用Any()而不是Where(),我总是只得到1个结果...我想将表达式传递给我的EF实现:

    public ICollection<T> GetEntriesWithPredicate(Expression<Func<T, bool>> predicate)
    {
        using (var ctx = new DataContext())
        {
            return query.Where(predicate).ToList();
        }
    }

1 个答案:

答案 0 :(得分:0)

class Program
{
    static void Main(string[] args)
    {
        var o = new Foo { };

        var f = o.GetEntitiesWithPredicate(a => a.MyProperty.Where(b => b.MyProperty > 0).ToList().Count == 2); // f.MyProperty == 9 true
    }
}

class Foo
{
    public ICollection<T> GetEntitiesWithPredicate(Expression<Func<T, bool>> predicate)
    {
        var t = predicate.Compile();

        var d = t.Invoke(new T { MyProperty = new List<Y> { new Y { MyProperty = 10 }, new Y { MyProperty = 10 } } });



        if (d) return new List<T> { new T { MyProperty = new List<Y> { new Y { MyProperty = 9 } } } };

        return null;
    }
}

class T
{
    public T() { }
    public List<Y> MyProperty { get; set; }
}

class Y
{
    public int MyProperty { get; set; }
}