如何用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
相关产品推荐
相关产品推荐

