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;
}
有沒有其他方式可以做,而不會使用太多的條件?任何幫助或建議,將不勝感激
你需要[表達式樹](https://msdn.microsoft.com/en-us/library/mt654263.aspx)。 –