包含“过滤器”的CONTAINS方法的LINQ语法

时间:2011-01-18 20:25:47

标签: c# linq linq-to-sql

这可能看起来有点“太多”,但这是在挑选我!

设想一个带有CheckBoxList的表单,该表单充当用户的包容性过滤器。

此用户填写表单,检查他们想要的过滤器中的哪些项目,然后关闭它们。

我正在寻找一种简洁的方法来编写以下LINQ语句:

如果未选中任何项目,则显示所有结果 其他 显示按用户选择过滤的结果

是否可以(如果是这样,如何)在不使用基本上是相同查询但没有Contains方法的条件语句的情况下编写它?

我尝试在我的Where子句中放置一个三元运算符,但编译器根本不喜欢它。

System.Collections.Generic.List catIds = new System.Collections.Generic.List();

              foreach (ListItem lstItemCategory in lstCategories.Items)
              {
                  if (lstItemCategory.Selected)
                  {
                      catIds.Add(Convert.ToInt64(lstItemCategory.Value));
                  }
              }

              var qry = from rategroup in rategroups
                        from rate in rategroup.Rates
                        orderby rate.RateClass.Id descending
                        select new
                        {
                            Category = rate.Product.ProductCategories[0].Category.Description,
                            rate.Product.Description,
                            Carrier = rate.CarrierName,
                            Id = rate.Product.ProductCategories[0].Id
                        };


              this.gvSchedule.DataSource = qry.Where(x => catIds.Contains(x.Id)).OrderBy(x => x.Category).ThenBy(x => x.Carrier).ToArray();
              this.gvSchedule.DataBind();

1 个答案:

答案 0 :(得分:3)

为什么不这样做:

var filteredQry = catIds.Any() ? qry.Where(x => catIds.Contains(x.Id)) : qry;
this.gvSchedule.DataSource = filteredQry.OrderBy(x => x.Category)
                                        .ThenBy(x => x.Carrier)
                                        .ToArray();

或者:

if(catIds.Any())
    qry = qry.Where(x => catIds.Contains(x.Id));

this.gvSchedule.DataSource = qry.OrderBy(x => x.Category)
                                .ThenBy(x => x.Carrier)
                                .ToArray();

你也可以尝试使用Expression<Func<Foo, bool>>过滤器,并根据条件将其分配给'always true'谓词或真正的过滤器,但由于涉及匿名类型,这将有点困难。