2011-03-18 18 views
1

私のlinqクエリではほとんど条件を適用しません。私のシナリオでは、私はテーブルからレコードをフェッチしている場合、ユーザーがいくつかの条件を選択し、条件を適用します。だから私は何をしたいのかlinqクエリに文字列条件を埋め込む方法

var linq = from p in Post select p 
//now if user apply that condition 
string id = "1"; //Here 1 is what user inputs 
string condition = where p.id == id 
//then it executes query like this 
linq = from p in Post condition select p 

は私がLINQでこれを行うことができYESである場合、その後どのように

+0

は、常に状態を持つことが保証されていますか?またはユーザーが指定した場合にのみ条件を欲しいですか? – Roly

+0

はいユーザーが条件を指定する場合は適用し、そうでない場合はすべて表示します。 –

+0

http://stackoverflow.com/questions/848415/linq-dynamic-where-clause – Roly

答えて

4
var linq = from p in Post select p; 

//now if user apply that condition 
string id = "1"; //Here 1 is what user inputs 

if (!String.IsNullOrEmpty(id)) 
{ 
    linq = linq.Where(p => p.id == id); 
} 

return linq.ToList(); // or whatever you want to do with it at this point 
1

あなたはおそらく、あなたが条件の使用式を作りたいか、複雑で動的なLINQや依存を調べることになるでしょう木

あなたがしようとする場合があります:

string id = "1"; 
string condition = "p.id == " + id; 
var linq = from p in Post 
      where (condition) 
      select p; 

またはラムダと:

string id = "1"; 
string condition = "p => p.id == " + id; 
var linq = Post.Where(condition).SingleOrDefault(); 

は、次を参照してください。

Scott Gu's post on Dynamic Linq

Querying Entity with LINQ using Dyanmic Field Name

Basics of Linq Expression Trees

+2

私は式の木がこのために残忍であると思うのです – Roly

+0

合意しましたが、Franzがユーザーがフィールドを選択する検索機能検索と同様に条件式を使用すると、式ツリーは答えになります –

+0

var linq = Post.Where(条件).SingleOrDefault();この行はコンパイルしてもエラーになりません –

関連する問題