c# - 比较项目列表然后拆分

标签 c#

我创建了 3 个不同的列表变量,其中包含用于添加、删除和更新的数据。我必须将数据与 ExistingItemsNewItemList 进行比较,然后如果 ExistingItems 有数据但 NewItemList 没有则该项目应该列在 deleteList 变量中。像这样,如果 NewItemList 有数据但 ExistingItems 没有,那么该项目应该列在 addList 中。最后,当 ExistingItems NewItemList 匹配时,它将被添加到 updateList。请注意 ID 是唯一的,用于比较匹配和 ExistingItemsNewItemList 这两个数据模型类型与 Item 类完全相同。我已经尝试使用 Except() 方法过滤 addList 但这对我不起作用,因为我只想按 ID 而不是价格进行比较。

主要代码:

var addList = new List<Item>();
var updateList = new List<Item>();
var deleteList = new List<Item>();

addList = EixistingItems.Except(NewItemList).ToList();

元素等级:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestProj.Models
{
    Class Item 
    {
        public int ID { get; set; }
        public int Price { get; set; }
    }
}

最佳答案

我认为您需要的是一个相等比较器。它允许在 Except linq 语句中控制比较。然后,您可以定义仅检查 ID 属性:

var deleteList = ExistingItems.Except(NewItemList, new ItemComparer()).ToList();
var addList = NewItemList.Except(ExistingItems, new ItemComparer()).ToList();

class Item
{
    public int ID { get; set; }
    public int Price { get; set; }
}
class ItemComparer : IEqualityComparer<Item>
{
    public bool Equals(Item x, Item y)
    {
        return x.ID == y.ID;
    }

    public int GetHashCode(Item obj)
    {
        return obj.GetHashCode();
    }
}

关于c# - 比较项目列表然后拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51415160/

相关文章:

c# - 在 DbContext 中访问 HttpContext.Current.User.Identity.Name

c# - 自定义 CodeAccessSecurityAttribute

c# - swagger oauth 安全定义

c# - Ienumerable concat 不适用于每个循环

c# - 在代码中初始化用户控件不起作用 - MVVM WPF

c# - AppDomainSetup.PrivateBinPath 与 Environment.SetEnvironmentVariable

c# - 通过 JavaScript 将值分配给 Asp.net 标签,然后通过 C# session 对象传递时出现问题

c# - Unity C# - 数组索引超出范围

c# - Entity Framework 中基本实体的流畅配置

c# - 遍历数据中继器中所有行的最佳方法?