linq查询的任何方式来检查现有的选择?

时间:2012-06-20 09:10:23

标签: c# .net linq

我有一个优惠,可以是任意数量的类别。然而,我不希望这个提议出现两次或更多。

我想知道是否可能有一个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
                          }

         },

1 个答案:

答案 0 :(得分: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());