列表除了两个不同的类实例列表

时间:2017-11-13 08:55:48

标签: c#

我想将两个列表与两个不同类的对象进行比较。这些是类:

namespace AngularWebApplication.Models
{
    public class AggregationLevelConfigurationPresentation
    {
        public byte AggregationLevelConfigurationId { get; set; }
        public int ProductionOrderId { get; set; }
        public string Name { get; set; }
        [ ... ]
    }
}

public class AggregationLevelConfiguration : IEquatable<AggregationLevelConfiguration>
{
    public byte AggregationLevelConfigurationId { get; set; }
    public int ProductionOrderId { get; set; }
    public string Name { get; set; }
    [ ... ]
}

我想让presentations列表中的元素不在currentLevels中:

列出演示文稿; 列出currentLevels;

List<Models.AggregationLevelConfigurationPresentation> newLevels =
    presentations
        .Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId })
        .Except(currentLevels.Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId }))
        .ToList();

但是当我执行Except时,我收到以下错误:

Error   CS0029  Cannot implicitly convert type 
'System.Collections.Generic.List<<anonymous type: byte AggregationLevelConfigurationId, int ProductionOrderId>>' to 
'System.Collections.Generic.List<AngularWebApplication.Models.AggregationLevelConfigurationPresentation>'

我认为问题出在new { l.AggregationLevelConfigurationId, l.ProductionOrderId },但我不知道如何使用不同类别的对象列表来执行Except

我需要presentations列表中的对象,currentLevels使用AggregationLevelConfigurationIdProductionOrderId作为主键。

2 个答案:

答案 0 :(得分:4)

您的Execept - 查询会选择匿名类型,因此ToList不会创建List<AggregationLevelConfigurationPresentation>。您必须创建此类的实例:

List<AggregationLevelConfigurationPresentation> newLevels = presentations
        .Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId })
        .Except(currentLevels.Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId }))
        .Select(x => new AggregationLevelConfigurationPresentation 
        { 
            AggregationLevelConfigurationId = x.AggregationLevelConfigurationId,  
            ProductionOrderId = x.ProductionOrderId
         })
        .ToList();
  

我需要他们不在的演示文稿列表中的对象   currentLevels使用AggregationLevelConfigurationId和   ProductionOrderId作为主键。

然后你可以使用Join

var except = presentations
        .Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId })
        .Except(currentLevels.Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId }));

var newLevels = from x in except
                join p in presentations 
                on x equals new { p.AggregationLevelConfigurationId, p.ProductionOrderId }
                select p;
List<AggregationLevelConfigurationPresentation> newLevelList = newLevels.ToList();

答案 1 :(得分:0)

根据Evk评论,这就是我解决这个问题的方法:

List<Models.AggregationLevelConfigurationPresentation> newLevels =
     presentations.Where(p => !currentLevels.Any(l => p.AggregationLevelConfigurationId == l.AggregationLevelConfigurationId && p.ProductionOrderId == l.ProductionOrderId));