c# - 使用LINQ获取两个表之间的差异

标签 c# linq

我有一个现有的表和一个新表。 这些表至少包含两个需要检查的项目。 我需要做以下几件事

1) 获取不在新表中但在现有表中的项目列表。 - 所以它们可以被删除 2) 获取新表中但现有表中不存在的项目列表 - 以便可以添加它们

3) 获取两个表中都存在但现有表需要更新的项目列表

这是数据

var existingItems = new[] 
{ 
    new RetryItem { CellId = 1, Content = "Bob" }, 
    new RetryItem { CellId = 2, Content = "Bill" }, 
    new RetryItem { CellId = 3, Content = "Frank" }, 
    new RetryItem { CellId = 4, Content = "Tom" }, 
    new RetryItem { CellId = 5, Content = "Dick" }, 
    new RetryItem { CellId = 6, Content = "Harry" }, 
}; 

var newItemsLarger = new[] 
{ 
    new RetryItem { CellId = 1, Content = "Bob" }, 
    new RetryItem { CellId = 2, Content = "Bill" }, 
    new RetryItem { CellId = 3, Content = "Frank" }, 
    new RetryItem { CellId = 4, Content = "Tom now Thoams" }, 
    new RetryItem { CellId = 5, Content = "Dick now Dicky" }, 
    new RetryItem { CellId = 6, Content = "Harry Now Harriet" }, 
    new RetryItem { CellId = 7, Content = "Mary" }, 
    new RetryItem { CellId = 8, Content = "Mungo" }, 
    new RetryItem { CellId = 9, Content = "Midge" }, 
};

最佳答案

我认为这些可能会满足您的需求:

1)

var q1 = from c1 in existingItems
         join c2 in newItemsLarger 
         on new { c1.CellId, c1.Content } equals new {c2.CellId, c2.Content }
         select c1;

2)

var q2 = from c1 in newItemsLarger
         where !existingItems.Select(x => x.CellId).Contains(c1.CellId)
         select c1;

3)

var q3 = from c1 in existingItems
         join c2 in newItemsLarger on c1.CellId equals c2.CellId 
         where c1.Content != c2.Content
         select c2;

关于c# - 使用LINQ获取两个表之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8756014/

相关文章:

c# - 表达式树中未发生隐式转换

c# - 使用 ContinueWith 时如何捕获 OperationCanceledException

c# - 参数化查询

c# - 使用 T-SQL 返回多个结果集

c# - 用 LINQ 查询替换 foreach

c# - InvalidOperationException : type 'System.String' referenced from scope '' , 但未定义

c# - 在 C# 中创建 pocketsphinx 包装器的步骤

c# - 在 .Net 2.0 的 64 位应用程序中使用 32 位 DLL

c# - 使用 SymmetricDifference 比较两个文件夹的不相同文件

c# - 将一个集合分解成更小的集合,但重复项目