2016-01-11 55 views
6

我有這樣的方法:無法轉換lambda表達式爲委託類型

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 

爲了完成這項工作,我需要做些什麼改變?

編輯:

我使用實體框架6,如果我使用任何(),而不是在哪裏(),我總是隻得到1結果回來......我想表達的傳遞給我的EF-實現:

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

你可能是指'任何()'代替'凡()'。你的'Func '需要返回'bool',但'Where'正在返回'IEnumerable '。 – haim770

+0

那些不兼容。 –

+1

您確定您的意思是'GetEntitiesWithPredicate(Expression >謂詞)'而不僅僅是'GetEntitiesWithPredicate(Func predicate)'?你爲什麼需要'Expression'? –

回答

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; } 
} 
相關問題