gpt4 book ai didi

c# - 基于条件的Linq查询

转载 作者:太空宇宙 更新时间:2023-11-03 12:37:12 24 4
gpt4 key购买 nike

我必须检查 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;
}

有没有其他方法可以避免使用太多 if 条件?任何帮助或建议将不胜感激

最佳答案

定义将返回 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。您可以定义 bool 变量 fillTable 并在 if 语句中将其设置为 true。在 ifs 之后,您可以检查 if(!fillTable)return dt;

关于c# - 基于条件的Linq查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40477047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com