【问题标题】:Return a List<t> that has items that do not exist in a List<t> [duplicate]返回具有 List<t> 中不存在的项目的 List<t> [重复]
【发布时间】:2014-06-30 14:07:41
【问题描述】:

在 C# 中,我有以下类:

public class SQLColour
{
    public string ID { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
    public string CorporateID { get; set; }
}

我有一个名为 List1 的 List&lt;SQLColour&gt; 和一个名为 List2 的 List&lt;SQLColour&gt;

我如何返回 List&lt;SQLColour&gt;,其中的项目的 ID 存在于 List1 但不存在于 List2?

提前致谢

【问题讨论】:

标签: c# list class return compare


【解决方案1】:

我通常使用以下模式,因为Enumerable.Except 不接受泛型谓词:

// Find all IDs in List2, using a HashSet to improve bounds
var idsList2 = new HashSet(List2.Select(x => x.Id));

// Select from List1 only elements which ID does not appear in List2
var onlyList1ById = List1.Where(x => !idsList2.Contains(x.Id));

HashSet 不是必需的,但它有更好的界限,因此是我的标准模式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    相关资源
    最近更新 更多