Home >Backend Development >C++ >How Can I Efficiently Remove Items from One List That Exist in Another?
Remove an item from another list
Question:
How to loop through a generic list of items and remove them from another list of items?
Scene:
Consider the following hypothetical example:
<code>List<汽车> list1 = GetTheList(); List<汽车> list2 = GetSomeOtherList();</code>
The goal is to use a foreach loop to iterate through list1 and remove any items that are also present in list2. However, the foreach loop does not provide index-based methods.
Answer:
To achieve this you can use the Except method:
<code>List<汽车> result = list2.Except(list1).ToList();</code>
This will create a new list result containing items in list2 that are not present in list1. The Except method does not modify the original list.
Optimization:
To further optimize your code, you can eliminate the need for temporary variables:
<code>List<汽车> result = GetSomeOtherList().Except(GetTheList()).ToList();</code>
It is important to note that Except returns a new list containing the calculated differences, so it does not modify list1 or list2.
The above is the detailed content of How Can I Efficiently Remove Items from One List That Exist in Another?. For more information, please follow other related articles on the PHP Chinese website!