我有一个通过不同方式分配多个商品的对象。优惠仅适用于一个产品,而对象具有多个优惠。现在我想要一个对象的所有提供遵循一个特定的业务逻辑,只包含一次产品。
目前我已按如下方式实施:
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仅包含一次。
非常欢迎任何有助于我更好地解决这个问题的事情!
答案 0 :(得分: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();