You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中从两个列表拆分出已有记录与新记录列表?

按指定字段拆分已有/新供应商记录

你使用Intersect和Except未得到预期结果的核心原因是:默认情况下,这些方法对引用类型(如你的Supplier实体)会比较对象引用,而非你需要的stockNumber和supplierName字段值。哪怕两个对象的目标字段完全一致,只要是不同实例,就会被判定为不相等,因此交集为空、差集返回原列表全部内容。

解决方案1:自定义相等比较器(复用性高)

先实现一个自定义比较器,指定按stockNumber和supplierName匹配的规则:

public class SupplierEqualityComparer : IEqualityComparer<Supplier>
{
    public bool Equals(Supplier x, Supplier y)
    {
        if (x == null && y == null) return true;
        if (x == null || y == null) return false;
        // 按两个字段同时匹配判定相等,可根据需求调整大小写规则
        return x.stockNumber == y.stockNumber && 
               string.Equals(x.SupplierName, y.SupplierName, StringComparison.OrdinalIgnoreCase);
    }

    public int GetHashCode(Supplier obj)
    {
        if (obj == null) return 0;
        // 组合字段哈希值,确保同字段值的对象哈希码一致
        int hashStock = obj.stockNumber.GetHashCode();
        int hashName = obj.SupplierName?.GetHashCode() ?? 0;
        return hashStock ^ hashName;
    }
}

再用这个比较器执行拆分:

var comparer = new SupplierEqualityComparer();

// existingRecords:两组中stockNumber+SupplierName均匹配的记录(用于更新)
var existingRecords = existingSuppliers.Intersect(currentSuppliers, comparer).ToList();

// newRecords:currentSuppliers中未匹配的记录(用于插入)
var newRecords = currentSuppliers.Except(existingSuppliers, comparer).ToList();

解决方案2:手动LINQ筛选(快速实现)

如果不想额外定义比较器,直接用Where+Any筛选:

// existingRecords:currentSuppliers中与已有记录匹配的条目
var existingRecords = currentSuppliers.Where(current => 
    existingSuppliers.Any(existing => 
        existing.stockNumber == current.stockNumber && 
        string.Equals(existing.SupplierName, current.SupplierName, StringComparison.OrdinalIgnoreCase)
    )).ToList();

// newRecords:currentSuppliers中未匹配的条目
var newRecords = currentSuppliers.Where(current => 
    !existingSuppliers.Any(existing => 
        existing.stockNumber == current.stockNumber && 
        string.Equals(existing.SupplierName, current.SupplierName, StringComparison.OrdinalIgnoreCase)
    )).ToList();

内容的提问来源于stack exchange,提问作者GThree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 08:40:07