我有 2 个自定义类型列表。它们有一个名为 ItemID 的公共(public)元素,我想获取其中存在的所有元素,而不是另一个。有人有什么想法吗?
我基本上需要内部联接的对立面,但只需要 itemList 中不在 itemCheckoutList 中的元素,或者如果 IsComplete 为真,它们可以在 itemCheckoutList 中。这是我必须在 IsComplete 为 false 的情况下全部加入的内部联接:
itemList.Join(itemCheckoutList,
i => i.ItemID,
ic => ic.ItemID,
(i, ic) => new { itemList = i, itemCheckoutList = ic }).Where(x => x.itemCheckoutList.IsComplete == false).ToList();
最佳答案
我相信这就是您想要的。
itemList.Where(i => i.IsComplete ||
!itemCheckoutList.Any(ic => ic.ItemID == i.ItemID))
编辑
根据您的评论,我认为这就是您想要的。
itemList.Where(i => !itemCheckoutList.Any(ic => ic.ItemID == i.ItemID &&
!ic.IsComplete))
编辑
如果效率是一个问题,那么您需要为 itemCheckoutList
创建一个查找您可以重复使用或仅更改 itemCheckoutList
到 Dictionary<int, CheckOutItem>
正如 CodeCaster 所建议的那样。可以这样做。
// This should preferably be called just once but
// would need to be called whenever the list changes
var checkOutListLookup = itemCheckoutList.ToLookup(ic => ic.ItemID);
// and this can be called as needed.
var results = itemList.Where(i => !checkOutListLookup.Contains(i.ItemID) ||
checkOutListLookup[i.ItemID].IsComplete);
或者如果你把它设为 Dicionary<int, CheckOutItem>
它看起来像这样。
var results = itemList.Where(i => !checkOutDictionary.ContainsKey(i.ItemID) ||
checkOutDictionary[i.ItemID].IsComplete);
关于c# - 加入不同对象的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27533001/