I have 3 classes with the following properties:
OfferList class:
Guid Id
IEnumerable<Offer> Offers
Offer class:
Guid Id
Product Product
bool IsSealed
Product class:
Guid Id
An OfferList contains multiple Offers and an Offer has exact 1 Product.
How can I filter the OfferList to contain only Offers which are not sealed?
OfferList offerList = this.GetOfferList(id).Offers.Where(o => !o.IsSealed));
This returns an IEnumerable of type Offer instead of filtering the OfferList.
Interesting – it is a little confusing what you’re asking here.
I think you’re asking how to have
Offersfiltered in-place. If so:IEnumerable<T>is immutable (you have to cast to a concreteList<T>or similar to get mutability), andOffersis anIEnumerable<T>– so you can’t expectOffers.Where(o => !o.IsSealed));to change theOffersproperty – it returns an enumerable that filters the source as you enumerate it.Instead you’d do
Note, however, that this hides the original
Offersreference for any other code sharing thatOfferListinstance. It also doesn’t actually do any filtering until you start enumerating, either. But that’s often preferable. If you want it done there and then – use.ToArray()or.ToList()at the end of theWhereto force the enumeration to be done.A better approach would be to have a property or method on the
OfferListclass that returns a new enumerable on-demand:That way you’re not destroying the master enumerable.
Note that this code is susceptible to
Offersbeing null (aNullReferenceException) and that it’s not great to return null enumerables (return empty ones instead) – so if there is a chance thatOfferscan be null – then either stop that from happening; or use: