2016-11-08 100 views
2

我必須檢查col1,col2和col3值並選擇正確的linq查詢。基於條件的Linq查詢

這是我如何使用條件。

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; 
     } 

有沒有其他方式可以做,而不會使用太多的條件?任何幫助或建議,將不勝感激

+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); 
     } 

如果你想空DataTable是回報的時候所有COL1,COL2,COL3是空字符串或NULL。您可以在if語句中定義bool變量fillTable並將其設置爲true。之後,你可以檢查if(!fillTable)return dt;