【发布时间】:2017-11-13 08:55:48
【问题描述】:
我想将两个列表与两个不同类的对象进行比较。这些是类:
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中的元素:
列出演示文稿; 列出当前级别;
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。
我需要使用AggregationLevelConfigurationId 和ProductionOrderId 作为主键列出presentations 中不在currentLevels 中的对象。
【问题讨论】:
-
可以尝试改写标题吗?在阅读问题之前我无法理解它。
-
您正在选择匿名类型,那么为什么您期望
ToList创建一个List<AggregationLevelConfigurationPresentation>? -
@TimSchmelter 我希望有一个
List<Models.AggregationLevelConfigurationPresentation>。 -
我建议不要在这种情况下使用
Except。相反,你可以做类似presentations.Where(p => !currentLevels.Any(l => p.AggregationLevelConfigurationId == l.AggregationLevelConfigurationId)) -
@CodeCaster,在所有版本中,问题都是“我想获取演示列表中不在 currentLevels 中的元素”。编译器错误只是 OP 尝试这样做的副产品。
标签: c#