【问题标题】:Cannot convert lambda expression into delegate type无法将 lambda 表达式转换为委托类型
【发布时间】:2016-04-15 18:40:49
【问题描述】:

我有这样的方法:

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

【问题讨论】:

  • 您可能指的是Any(),而不是Where()。您的Func&lt;T, bool&gt; 需要返回bool,但Where 正在返回IEnumerable&lt;T&gt;
  • 那些不兼容。
  • 你确定你的意思是GetEntitiesWithPredicate(Expression&lt;Func&lt;T, bool&gt;&gt; predicate)而不仅仅是GetEntitiesWithPredicate(Func&lt;T, bool&gt;predicate)吗?为什么需要Expression
  • @PeterA.Schneider,因为在方法实现中,谓词被传递给一些 Linq 提供者(如实体框架)
  • @haim770 你能检查我的编辑吗

标签: c# lambda delegates


【解决方案1】:
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; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多