过滤列表比较两个列表与某些条件

时间:2012-10-02 06:17:37

标签: c# asp.net .net linq

我希望在通过Linq将两个列表进行比较后,准备一个CampaignDetails类型的列表。您可以在下面看到代码段:

List<CampaignDetails> str = service.GetActiveCampaignBySubCatId(lang, subCatId);  //List1
List<CampaignDetails> sploffer = service.GetSpecialOfferCampaignsForMobile(lang); // List2

List<CampaignDetails> CampList = new List<CampaignDetails>();        
foreach (var data in str)
{
    var CampL = (from offer in sploffer
                where offer.CampaignId != data.CampaignId
                select offer).ToList();
    CampList.Add(CampL);  // getting red mark here
}

CampaignDetail类:

public class CampaignDetail
{
    public int CampaignId { get; set; }
    public string CampaignName { get; set; }
    public string CampaignHeading { get; set; }
    public decimal OfferPrice { get; set; }
    public string CampaignDescription { get; set; }
}

这里出了什么问题?我无法根据上面的代码段过滤列表。我在CampList.Add(CampL);收到编译器警告:

  

最佳重载方法匹配   'System.Collections.Generic.List.Add(CampaignDetails) - 方法'   有一些无效的论点。

4 个答案:

答案 0 :(得分:2)

使用此方法:

 CampList.AddRange(CampL)

但是如果你使用SelectMany方法使用LINQ会更好:

var CampList = str.SelectMany(data => sploffer
                          .Where(offer => offer.CampaignId != data.CampaignId))
                  .ToList();

答案 1 :(得分:0)

代替Add使用AddRange方法将项​​目列表添加到现有列表中。

所以你的代码应该是:

foreach (var data in str)
{
    var CampL = (from offer in sploffer
                where offer.CampaignId != data.CampaignId
                select offer).ToList();
    CampList.AddRange(CampL);  // here change it to AddRange
}

Add中的方法CampList.Add(CampL)用于向列表中添加单个项目。由于您在上面的查询中选择了一个项目列表(CampL),因此无法使用Add方法插入现有列表CampList

答案 2 :(得分:0)

确保CampL属于CampaignDetails类型,然后您就可以将其添加到List类型的CampList中。

答案 3 :(得分:0)

var CampList  = from data in str
                from offer in sploffer
                where offer.CampaignId != data.CampaignId
                select offer;

//in case you want to materialize it,
//or in case you really need a list,
//but this could be unnecessary
CampList = CampList.ToList();