使用结果 LinqtoSQL 的差异比较整数列表和 add/remove 数据库中的行

Compare List of Integers and add/remove the rows in database using the difference in result LinqtoSQL

目前我正在使用 LinqtoSql 进行一个项目,我想为我当前的问题找到一个更简单的解决方案。

示例: 假设我有一个名为 Example 的 table 三行(值为 1,2,4) 现在在代码 (c#) 中,我将这些值作为整数列表获取(让我们将其命名为 lstExisting) 现在在我的方法中,我得到了另一个整数列表(比如 lstCurrent),整数值为 (1,2,3) 现在我想比较两个列表并找出整数的差异并更新数据库,因此根据我的示例,应添加值为 3 的新行并应删除值为 4 的现有行。 PS:(整数值将始终是唯一的,并且将为 1、2、3、4) Linq 解决方案更可取,但我不介意其他更简单的解决方案。

谢谢

您需要使用 Except 查找新项目和删除项目,例如:

var newItems = lstCurrent.Except(lstExisting).ToList();
var toBeDeletedItems = lstExisting.Except(lstCurrent).ToList();

稍后您可以迭代每个列表并相应地Add/Delete。

尝试使用 Contains()。有两个列表,你可以写这样的东西。它的作用是遍历您的方法列表中的每个项目并检查原始项目以查看其是否存在。

var lstExisting = getExistingList();
var lstCurrent = getCurrentList();

foreach(var currentInt in lstCurrent)
{
    if(!lstExisting.Contains(currentInt))
    {
        //insert currentInt
    }