c# - 如何将 LINQ 查询附加到彼此?

标签 c# linq

我有一个表单可以根据他们选择的内容过滤数据。

我试图将 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/

相关文章:

c# - 响应式扩展测试调度程序模拟时间流逝

sql - Linq 自连接组合键

c# - LINQ - 字典中的字典

c# - 从 DateTime 列中为每一天选择最小时间值

c# - 如何使用 LINQ 展平类中的嵌套字典

javascript - 从 @foreach 循环内部访问外部变量

c# - 我怎样才能在 WinForms 应用程序中捕获所有 'unhandled' 异常?

c# - ISubject 在哪里?

c# - 唯一选择用户名

c# - 使用结构作为字典的键和奇怪的事情正在发生