2016-11-08 102 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;