Odd Linq behavior with IList / IEnumerable

Posted by Aren B on Stack Overflow See other posts from Stack Overflow or by Aren B
Published on 2010-05-06T22:36:36Z Indexed on 2010/05/06 22:38 UTC
Read the original article Hit count: 330

Filed under:
|
|

I've got the following code:

    public IList<IProductViewModel> ChildProducts { get; set; }
    public IList<IProductViewModel> GiftItems { get; set; }
    public IList<IProductViewModel> PromoItems { get; set; }

    public IList<IProductViewModel> NonGiftItems
    {
        get
        {
            return NonPromoItems.Except(GiftItems, new ProductViewModelComparer()).ToList();
        }
    }

    public IList<IProductViewModel> NonPromoItems
    {
        get
        {
            return ChildProducts.Where(p => !p.IsPromotion).ToList();
        }
    }

So basically, NonPromoItems is (ChildProducts - PromoItems) and NonGiftItems is (NonPromoItems - GiftItems)

However When:

ChildProducts = IEnumerable<IProductViewModel>[6] PromoItems = IEnumerable<IProductViewModel>[1] where item matches 1 item in ChildProducts GiftItems = IEnumerable<IProductViewModel>[0]

My Result is

NonPromoItems = IEnumerable<IProductViewModel>[5] This is Correct NonGiftItems = IEnumerable<IProductViewModel>[4] This is Incorrect

Somehow an Except(...) is removing an item when given an empty list to subtract.

Any ideas anyone?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET