试图创建一个搜索,我需要动态地做一个orelse

时间:2014-01-10 16:21:39

标签: c# linq

我为日志表创建了一个搜索屏幕。我给用户提供了通过复选框选择他们想要显示的应用程序的选项。如果他们愿意,他们可以选择多个程序,或者至少我想这样做。

无论如何,我有以下问题:

     var qry = from logs in model.Logs
                where logs.LogDateTime > dateTimePicker_Start.Value &&
                      logs.LogDateTime < dateTimePicker_End.Value
                select logs;

      Guid tokenid;
      if (Guid.TryParse(textBox_TokenId.Text, out tokenid))
      {
        qry = qry.Where(x => x.TokenId == tokenid);
      }

      if (checkBox_DisplayErrors.Checked)
      {
        qry = qry.Where(x => x.IsException);
      }

      if (checkBox_WebPortal.Checked)
      {
        qry = qry.Where(x => x.SourceEnum == "WebPortal");
      }

      if (checkBox_SubService.Checked)
      {
        qry = qry.Where(x => x.SourceEnum == "SubService");
      }

      if (checkBox_TruckRouting.Checked)
      {
        qry = qry.Where(x => x.SourceEnum == "TruckRouting");
      }

      if (checkBox_SuburbanHub.Checked)
      {
        qry = qry.Where(x => x.SourceEnum == "SuburbanHub");
      }

      if (checkBox_DisplayWarnings.Checked)
      {
        qry = qry.Where(x => x.IsWarning);
      }

      if (!string.IsNullOrWhiteSpace(textBox_Contains.Text))
      {
        qry = qry.Where(x => x.Message.Contains(textBox_Contains.Text));
      }

      qry = qry.OrderByDescending(x => x.LogDateTime);

      var nqry = qry;

我需要以下字段才能成为一个角色:

checkBox_SuburbanHub
checkBox_WebPortal
checkBox_TruckRouting
checkBox_SubService

因此,如果他们检查其中一个或多个,则x.SourceEnum字段可以是已检查项之一。

我如何将这些结合起来,但仍然取决于他们是否已经检查过它们?

1 个答案:

答案 0 :(得分:3)

您可以将它们全部添加到列表中,然后使用contains执行orelse(实际上生成in子句),如下所示:

        var SourceEnumList = new List<string>();
        if (checkBox_WebPortal.Checked)
        {
            SourceEnumList.Add("WebPortal");
        }

        if (checkBox_SubService.Checked)
        {
            SourceEnumList.Add("SubService");
        }

        if (checkBox_TruckRouting.Checked)
        {
            SourceEnumList.Add("TruckRouting");
        }

        if (checkBox_SuburbanHub.Checked)
        {
            SourceEnumList.Add("SuburbanHub");

        }
        if (SourceEnumList.Any())
        {
            qry = qry.Where(x => SourceEnumList.Contains(x.SourceEnum) );
        }