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)。 –