LINQ syntax for CONTAINS with filter enabled

It may seem a bit "a lot", but it picks me!

Present a form with CheckBoxList that acts as an inclusive filter for the user.

This user fills out a form, checks what elements in the filter they want, and from them.

I am looking for a concise way to write the following LINQ statement:

If NO elements are checked, show all results . Show results filtered by user choice.

Is it possible (and if so, how) to write this without using a conditional statement, which is basically the same query, but without the Contains method?

I tried putting the ternary operator in the Where clause, but the compiler didn't like that at all.

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();
+3
source share
1 answer

Why not just do:

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();

Or:

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

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

You can also try using a filter Expression<Func<Foo, bool>>and assign it to the always-true predicate or the true filter, depending on the condition, but it will be a bit complicated, since an anonymous type is used.

+3
source

Source: https://habr.com/ru/post/1786229/


All Articles