0

我有一个报价,可以是任意数量的类别。但是,我不希望该提议出现两次或更多。

我想知道是否有可能有一个 where 子句来确定该提议是否已经存在于该 select 语句中,如果是这样显然可以忽略它。

这是 linq 查询:

Offers = from o in offerCategories
         orderby o.RewardCategory.Ordering, o.Order  
         where o.RewardOffer.IsDeleted == false
         select new OfferOverviewViewModel
         {
             Partner = o.RewardOffer.Partner,
             Description = String.Format("{0} {1}", o.RewardOffer.MainTitle, o.RewardOffer.SecondaryTitle),
             OfferId = o.OfferId,
             FeaturedOffer = o.RewardOffer.FeaturedOfferOrder.HasValue,
             Categories = from c in offerCategories.Where(oc => oc.OfferId == o.OfferId)
                          orderby c.RewardCategory.Ordering
                          select new CategoryDetailViewModel
                          {
                              Description = c.RewardCategory.DisplayName
                          }

         },
4

1 回答 1

2

你可以使用 Distinct(),但是你的 viewmodel 应该覆盖 Equals,或者你需要一个 EqualityComparer:

public class OfferEqualityComparer: IEqualityComparer<OfferOverviewViewModel> {

   public bool Equals(OfferOverviewViewModel x, OfferOverviewViewModel y) {
      return Equals(x.OfferId, y.OfferId);
   }

   public int GetHashCode(OfferOverviewViewModel x) {
      return x.OfferId.GetHashCode();
   }

}

Offers = (from o in offerCategories
                     orderby o.RewardCategory.Ordering, o.Order  
                     where o.RewardOffer.IsDeleted == false
                     select new OfferOverviewViewModel
                     {
                         Partner = o.RewardOffer.Partner,
                         Description = String.Format("{0} {1}", o.RewardOffer.MainTitle, o.RewardOffer.SecondaryTitle),
                         OfferId = o.OfferId,
                         FeaturedOffer = o.RewardOffer.FeaturedOfferOrder.HasValue,
                         Categories = from c in offerCategories.Where(oc => oc.OfferId == o.OfferId)
                                      orderby c.RewardCategory.Ordering
                                      select new CategoryDetailViewModel
                                      {
                                          Description = c.RewardCategory.DisplayName
                                      }

                     })
   .Distinct(new OfferEqualityComparer());
于 2012-06-20T09:33:43.327 回答