Linq根据条件查询

时间:2016-11-08 00:29:34

标签: c# performance entity-framework linq c#-4.0

我必须检查col1,col2和col3值并选择正确的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;
        }

如果不使用太多条件,还有其他办法吗?任何帮助或建议将不胜感激

1 个答案:

答案 0 :(得分: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,col3为空字符串或null时返回空DataTable。您可以在if语句中定义bool变量fillTable并将其设置为true。在ifs之后,您可以查看if(!fillTable)return dt;