c# - 加入不同对象的列表

标签 c# linq lambda

我有 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 创建一个查找您可以重复使用或仅更改 itemCheckoutListDictionary<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/

相关文章:

c# - 需要自定义货币格式才能与 String.Format 一起使用

javascript - 在 Ajax 中调用 Controller 函数

c# - LINQ 使所有方法异步

c# - 让方法语法中的查询语法?

c++ - 在 C++11 lambda 语法中,堆分配的闭包?

c# - 已启用的组合框控件在 Windows 10 中看起来已禁用?

c# - 从 Matlab 到 C#

c# - 如何创建一个 linq 语句来获取项目列表并将它们分成每组 50 个

c# - 使用 lambda 表达式连接表

c++ - 将带有 unique_ptr 的可变 lambda 传递给 const& std::function