首页 > 解决方案 > 从对象列表中查找唯一对象的最简单方法

问题描述

在我的项目中,我有两个实体,第一个是Business entity(BE)来自客户(或)客户,另一个Data Entity(DE)是来自数据库。

收货.cs

public class GoodsReceipt
    {
        public Guid Id { get; set; }
        public string PurchaseOrderId { get; set; }
        public string Note { get; set; }
        public virtual ICollection<GoodsReceiptProduct> GoodsReceiptProducts { get; set; }
    }

GoodsReceiptProduct.cs

public class GoodsReceiptProduct
    {
        public Guid Id { get; set; }
        public Guid GoodsReceiptId { get; set; }
        public Guid PurchaseOrderId { get; set; }
        public Guid ProductId { get; set; }
    }

我的要求是获取新项目是否在集合中added或集合updated中。而在 GoodsReceiptProduct 中对于列表中的所有对象来说都是唯一的。deletedGoodsReceiptProductsPurchaseOrderId

用户将BE GoodsReceipt连同一组GoodsReceiptProduct. 那么从列表中获取该唯一对象DE的可能方法是什么,在将该列表与服务器上的现有列表进行比较时,该对象可能会被添加、更新或删除。

标签: c#asp.net-web-apiasp.net-coreasp.net-core-2.1

解决方案


我猜您想比较 2 个列表并确定哪些记录是新添加的、删除的或保持不变的。而不是找到一个独特的对象。

为此,您可以使用except & Intersect

例如:

List<GoodsReceiptProduct> existingListInDataEntity = GetExistingList();
List<GoodsReceiptProduct> modifiedListInBusinessEntity = GetBusinessList();

var newAddedItems = modifiedListInBusinessEntity.Except(existingListInDataEntity);
var deletedItems = existingListInDataEntity.Except(modifiedListInBusinessEntity);
var sameItems = modifiedListInBusinessEntity.Intersect(existingListInDataEntity);

推荐阅读