LINQ syntax for CONTAINS method with an inclusive "filter"
This may seem a little "much", but this is picking at me!
Envision a form with a CheckBoxList that acts as an inclusive filter for a user.
This user fills out a form, checks off which items in the filter they want, and off they go.
I'm looking for a concise way to write the following LINQ statement:
If NO items are checked开发者_高级运维, show all results else Show results filtered by user selection
Is it possible (and if so, how) to write this without using a conditional statement that basically is the same query, but without the Contains method?
I tried putting a ternary operator in my Where clause, but the compiler didn't like it 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();
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 could also try using an Expression<Func<Foo, bool>>
filter and assigning it to an 'always true' predicate or the genuine filter depending on the condition, but this will be slightly difficult since an anonymous type is involved.
精彩评论