-1

在通过 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)-Method' 的最佳重载方法匹配有一些无效参数。

4

4 回答 4

2

使用此方法:

 CampList.AddRange(CampL)

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

var CampList = str.SelectMany(data => sploffer
                          .Where(offer => offer.CampaignId != data.CampaignId))
                  .ToList();
于 2012-10-02T06:20:48.370 回答
0

Insetead 的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
}

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

于 2012-10-02T06:21:05.650 回答
0

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

于 2012-10-02T06:21:14.990 回答
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();
于 2012-10-02T06:48:28.223 回答