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

6
我有一个如下的方法:

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(),我总是只得到一个结果...我想将表达式传递给我的EF实现:

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

11
дҪ еҸҜиғҪжғідҪҝз”Ё Any() иҖҢдёҚжҳҜ Where()гҖӮдҪ зҡ„ Func<T, bool> йңҖиҰҒиҝ”еӣһ boolпјҢдҪҶжҳҜ Where иҝ”еӣһзҡ„жҳҜ IEnumerable<T>гҖӮ - haim770
1
你确定你需要使用 GetEntitiesWithPredicate(Expression<Func<T, bool>> predicate) 而不是仅仅的 GetEntitiesWithPredicate(Func<T, bool>predicate) 吗?为什么你需要这个 Expression - Peter - Reinstate Monica
@GrayFox,你现有的方法已经将内部的Where()调用包装到了Entity Framework中... - haim770
让我们在聊天中继续这个讨论。 - GrayFox
如果使用Any()或Where()似乎是不必要的,那么从表达式委托中访问集合会令人困惑。我认为你最好希望使用看起来像这样的语法... service.GetEntitiesWithPredicate(x => x.Text.Contains(SearchText)); - blins
显示剩余6条评论
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接