2016-11-08 24 views
2

col1、col2、col3の値をチェックし、正しいlinqクエリを選択する必要があります。条件に基づくLinqクエリ

これはif条件を使用しています。

public DataTable GetRawData(string col1, string col2, string col3) 
     { 
      IQueryable<IF_Table> result = null; 
      DataTable dt = new DataTable(); 
      dt.Columns.Add("Id"); 
      dt.Columns.Add("DetailId"); 
      dt.Columns.Add("Description"); 
      DataRow row = null; 
      if (!string.IsNullOrEmpty(col1)) 
      { 
       result = db.IF_Table.Where(x => x.col1 == col1); 
      } 
      if (!string.IsNullOrEmpty(col2)) 
      { 
       result = db.IF_Table.Where(x => x.col2 == col2); 
      } 
      if (!string.IsNullOrEmpty(col3)) 
      { 
       result = db.IF_Table.Where(x => x.col3 == col3); 
      } 
      if (!string.IsNullOrEmpty(col1) && !string.IsNullOrEmpty(col2)) 
      { 
       result = db.IF_Table.Where(x => x.col1 == col1 && x.col2==col2); 
      } 
      if (!string.IsNullOrEmpty(col1) && !string.IsNullOrEmpty(col3)) 
      { 
       result = db.IF_Table.Where(x => x.col1 == col1 && x.col3 == col3); 
      } 
      if (!string.IsNullOrEmpty(col2) && !string.IsNullOrEmpty(col3)) 
      { 
       result = db.IF_Table.Where(x => x.col2 == col2 && x.col3 == col3); 
      } 
      if (!string.IsNullOrEmpty(col1) && !string.IsNullOrEmpty(col2) && !string.IsNullOrEmpty(col3)) 
      { 
       result = db.IF_Table.Where(x =>x.col1==col1 && x.col2 == col2 && x.col3 == col3); 
      } 
      foreach (var rowObj in result) 
      { 
       row = dt.NewRow(); 
       dt.Rows.Add(rowObj.Id, rowObj.DetailId,rowObj.Description); 
      } 
      return dt; 
     } 

あまりにも多くのif条件を使用せずに行う他の方法はありますか?任意の助けや提案をいただければ幸いです

+0

[式ツリー](https://msdn.microsoft.com/en-us/library/mt654263.aspx)が必要です。 –

答えて

1

db.IF_Tableを返すベースクエリを定義してください。その後、この結果を中心にクエリを作成します。この3 ifは、すべてのケースをカバーする必要があります。

 IQueryable<IF_Table> result = db.IF_Table; 
     if (!string.IsNullOrEmpty(col1)) 
     { 
      result = result.Where(x => x.col1 == col1); 
     } 
     if (!string.IsNullOrEmpty(col2)) 
     { 
      result = result.Where(x => x.col2 == col2); 
     } 
     if (!string.IsNullOrEmpty(col3)) 
     { 
      result = result.Where(x => x.col3 == col3); 
     } 

あなたはときに、すべてのCOL1、COL2空DataTableを返すことにしたい場合は、COL3は、空の文字列またはnullです。 bool変数fillTableを定義し、ifステートメントでtrueに設定することができます。あなたが確認できるifsの後if(!fillTable)return dt;

関連する問題