2011-02-19 96 views
3

在Linq to SQL中我有一個表達式返回一個int,並且我想根據返回一個布爾值的那個表達式創建一個表達式。 int可用於OrderBy(score),布爾值可用於Where(ifScore)。我無法弄清楚如何使用分數來定義ifScore,並希望得到一些幫助。在Int表達式中創建一個bool Linq to SQL表達式

Expression<Func<Model, int>> score = p => 
      (testList.Count() > 0 && p.Name.Contains(testList.FirstOrDefault()) ? 1 : 0); 

Expression<Func<Model, bool>> ifScore = p => 
      //how to say if score > 2 
+2

你的第一個表達式只能返回1或0的整數,這基本上是一個真/假。不知道你在努力完成什麼 – Aducci

回答

2

我不知道有多好,這將與LINQ發揮到SQL,但你可以用Expression.GreaterThan創建相應的二進制表達,那麼它只是創造從右邊Expression<TDelegate>的問題。

var body = Expression.GreaterThan(score.Body, Expression.Constant(2)); 
var ifScore = Expression.Lambda<Func<Model, bool>>(body, score.Parameters); 

最終的表達看起來像:

p => ((testList.Count() > 0 
     && p.Name.Contains(testList.FirstOrDefault()) ? 1 : 0) > 2 

當然,這看起來有點荒謬的,因爲它可以永遠是真實的。你確定你打算這麼做嗎?也許你真的想與10比較,而不是平等?

+0

謝謝。這只是一個例子,但是你的2排頂部完美無缺。 –