ashcow (2) [Avatar] Offline
#1
Hello All,

Does the Predicate Builder work with Linq to Objects?

I have used it with Linq To Sql but am not having any luck applying it to an IList of Entities

Expression<Func><BroadbandProductEntity, bool>> conditions = PredicateBuilder.True<BroadbandProductEntity>();

if (_filter.DownloadLimitId != null)
{
conditions.And(bbp => bbp.DownloadLimitId == _filter.DownloadLimitId);
}

var filteredProducts = _availableProducts.Where(conditions);


where availableProducts is an

IList<BroadbandProductEntity> _availableProducts;
jwooley (123) [Avatar] Offline
#2
Re: PredicateBuilder with Linq To Objects
It appears that the PredicateBuilder extends IQueryable. LINQ to Objects works over IEnumerable, not IQueryable. As we discuss in chapter 7, IQueryable extends IEnumerable by adding the Expression property which contains the expression tree. It is this expression tree that the Predicate Builder uses to allow for added functionality.
fabrice.marguerie (224) [Avatar] Offline
#3
Re: PredicateBuilder with Linq To Objects
Ashley,

As we show in section 5.1.3 (Dynamic queries), you don't need something like PredicateBuilder to do what you're trying to achieve.
If there are no ORs in your conditions, you can simply add more Where calls to your original query. And this works for LINQ to Objects and LINQ to SQL.

filteredProducts = [your base query];
if (_filter.DownloadLimitId != null)
{
filteredProducts = filteredProducts.Where(bbp => bbp.DownloadLimitId == _filter.DownloadLimitId);
}
if (_filter.OtherCriterion != null)
{
filteredProducts = filteredProducts.Where([other filter]);
}
...

Fabrice
ashcow (2) [Avatar] Offline
#4
Re: PredicateBuilder with Linq To Objects
Thank you and Merci.

Thats excellent.