2

我有一个对象,其中有多个通过不同方式分配的优惠。一个商品只针对一个产品,而一个对象有多个商品。现在我想要一个对象的所有报价都遵循一个产品只包含一次的特定业务逻辑。

目前我已经实现如下:

List<Offer> offers = new List<Offer>();
List<Product> products = new List<Product>();                
this.AddOffersToList(offers, products, ov.Offers.Where(o => o.OfferType == composedOffer));
this.AddOffersToList(offers, products, ov.Offers.Where(o => o.OfferType == simpleOffer));
this.AddOffersToList(offers, products, ov.ComposedOfferList.Offers);
this.AddOffersToList(offers, products, ov.SimpleOfferList.Offers);

AddOffersToList 方法:

private void AddOffersToList(List<Offer> offers, List<Product> products,IEnumerable<Offer> newOffers)
{
    foreach (Offer offer in newOffers)
    {
        // add offer only if the product is not contained yet
        if (!products.Contains(offer.Product))
        {
            offers.Add(offer);
            products.Add(offer.Product);
        } 
    }
}

这似乎不是最优雅和性能最好的方式。“约束”是 AddOffersToList 方法调用的顺序,并且 Product 仅包含一次。

任何可以帮助我更好地解决这个问题的东西都非常受欢迎!

4

1 回答 1

1

此代码与您所相信的“等效”。

var offers = ov.Offers.Where(o => o.OfferType == composedOffer)
    .Concat(ov.Offers.Where(o => o.OfferType == simpleOffer))
    .Concat(ov.ComposedOfferList.Offers)
    .Concat(ov.SimpleOfferList.Offers)
    .GroupBy(offer => offer.Product)
    .Select(group => group.First())
    .ToList();

var products = offers.Select(offer => offer.Product).ToList();
于 2012-11-17T19:30:17.150 回答