我有一个表单可以根据他们选择的内容过滤数据。
我试图将 linq 查询附加到彼此,以便最终结果是他们在屏幕上选择的结果。
这是我的代码:
private void button_Search_Click(object sender, EventArgs e)
{
using (var model = new SuburbanPortalEntities())
{
var qry = from logs in model.Logs
select logs;
Guid corpid;
if (Guid.TryParse(textBox_CorporationGuid.Text, out corpid))
{
qry = from logs in model.Logs
where logs.CorporationId == corpid
select logs;
}
Guid tokenid;
if (Guid.TryParse(textBox_TokenId.Text, out tokenid))
{
qry = from logs in model.Logs
where logs.TokenId == tokenid
orderby logs.LogDateTime descending
select logs;
}
if (checkBox_DisplayErrors.Checked)
{
qry = from logs in model.Logs
where logs.IsException
select logs;
}
if (checkBox_DisplayWarnings.Checked)
{
qry = from logs in model.Logs
where logs.IsWarning
select logs;
}
dataGridView1.DataSource = qry;
}
}
我运气不好。最后一个 qry 是我的 datagridview 上显示的内容。
有人可以告诉我我做错了什么吗?
谢谢!
最佳答案
这里发生的是你重新定义了 qry
每次都来自您的源数据。 qry
是一个 IEnumerable<T>
与 logs
相同, 所以你应该能够像这样替换你的代码:
var qry = model.Logs;
if( // Condition )
qry = qry.Where(x => x.CorporationId == corpId);
if( // Another condition)
qry = qry.Where(x => x.IsException);
在此设置结束时,qry
将所有被选中的成分Where
条款,并且应该只产生您正在寻找的项目。
关于c# - 如何将 LINQ 查询附加到彼此?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18149153/