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

如何用C# LINQ筛选需插入现有表的新数据?

筛选传入表中未存在的行(C# LINQ实现)

数据结构定义

首先定义对应的数据类来映射表结构:

// 现有表实体(包含ID和Codes集合)
public class ExistingItem
{
    public int ID { get; set; }
    public HashSet<int> Codes { get; set; }
}

// 传入表实体(仅包含Codes集合)
public class IncomingItem
{
    public HashSet<int> Codes { get; set; }
}

示例数据初始化

// 初始化现有表数据
var existingItems = new List<ExistingItem>
{
    new ExistingItem { ID = 1, Codes = new HashSet<int> { 1, 2, 3 } },
    new ExistingItem { ID = 2, Codes = new HashSet<int> { 4, 5, 6, 7 } },
    new ExistingItem { ID = 3, Codes = new HashSet<int> { 8, 9, 10, 11 } }
};

// 初始化传入表数据
var incomingItems = new List<IncomingItem>
{
    new IncomingItem { Codes = new HashSet<int> { 1, 2, 3 } },
    new IncomingItem { Codes = new HashSet<int> { 4, 5, 6, 7 } },
    new IncomingItem { Codes = new HashSet<int> { 13, 14, 15, 16 } }
};

LINQ查询实现

核心逻辑是提取现有表中所有Codes集合,筛选传入表中Codes集合完全不匹配现有表任何一项的条目,用HashSet.SetEquals判断两个集合是否包含完全相同的元素:

var newItemsToInsert = incomingItems
    .Where(incoming => !existingItems
        .Any(existing => existing.Codes.SetEquals(incoming.Codes)))
    .ToList();

执行后,newItemsToInsert将只包含Codes = {13,14,15,16}的传入项,符合预期输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 13:07:11