2011-07-21 11 views
0

私はLinqクエリを書いています。 if条件に基づいてクエリに連結する方法はありますか?クエリのLinq to Entity - 条件を連結する方法

などが

from res in _db.Person 
    where res.Departments.ID == deptId 
    select res; 

と私は真の条件を持っている場合、私はそれが「AND」タイプの条件を実装

from res in _db.Person 
    where res.Departments.ID == deptId && res.Departments.Type == deptType 
    select res; 
+0

を使用したいと思うかもしれ変数条件

from res in _db.Person where res.Departments.ID == deptId && (!condition || res.Departments.Type == deptType) select res; 

バージョンであります別のコメントにORを必要としていると述べました。 –

+0

このアプローチを使用してください。http://stackoverflow.com/questions/21512230/where-clause-with-multiple-unknown-conditions –

答えて

3

はないか、要求された

from res in _db.Person 
where res.Departments.ID == deptId || (condition && res.Departments.Type == deptType)) 
select res; 

代替として、あなたが必要とロジックを明確にしてくださいでしたpredicate builder

5

ようなものにしたいと思います簡単です - と簡単に拡張メソッド構文を使用してWhereを複数回呼び出します。

EDIT: 「OR」機能が必要な場合は、式ツリーを使いこなす必要があるため、最初から少しトリッキーです。私はあなたがPredicateBuilderライブラリを使用することをお勧め:

Expression<Func<Person, bool> predicate = res => res.Departments.ID == deptId; 
if (deptType != null) 
{ 
    predicate = predicate.Or(res => res.Departments.Type == deptType); 
} 
IQueryable<Person> people = _db.Person.Where(predicate); 
+0

私はこれが第1位となると思います。 私は必要ですOR – Riz

+0

@eFriend:あなたがORを必要とした場合、あなたはなぜあなたの質問に答えましたか? ORは実装するのがはるかに困難です。 –

+0

は私の間違いでした、申し訳ありません。 ORの実装を提案できますか? – Riz

1

私はこのようなものだろう:

var result = _db.Person.Where(x=>x.Departments.ID == deptId); 
if(myCondition) 
    result = result.Where(x=>x.Departments.Type == deptType); 

クエリはあなたがresultを列挙しようとするまで、実際には実行されませんので、あなたが長いなどの条件を追加し続けることができますが好きなように。あなたの条件を仮定し

+0

私はこれが第1位、第2位、どこですか? 私はORが必要です – Riz

関連する問題