从对象列表中找到唯一对象的最简单方法[重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

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

GoodsReceipt.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还是deletedGoodsReceiptProducts。 GoodsReceiptProduct中的PurchaseOrderId对于列表中的所有对象都是唯一的。

用户将发送BE GoodsReceipt以及GoodsReceiptProduct的集合。那么从列表中获取该唯一对象的可能方法是什么,可以在将该列表与服务器上的现有DE列表进行比较时添加,更新或删除。

c# asp.net-web-api asp.net-core asp.net-core-2.1
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);

-1
投票

在IEnumerables中使用Distinct()

例如:

var YourList = List<GoodsReceiptProduct>();

//YourList = propulate the list here;

var UniqueList = YourList.Distinct();
© www.soinside.com 2019 - 2024. All rights reserved.