Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am learning to write lambda expressions, and I need help on how to remove all elements from a list which are not in another list.

var list = new List<int> {1, 2, 2, 4, 5};
var list2 = new List<int> { 4, 5 };

// Remove all list items not in List2
// new List Should contain {4,5}    
// The lambda expression is the Predicate.
list.RemoveAll(item => item. /*solution expression here*/ );

// Display results.
foreach (int i in list)
{
    Console.WriteLine(i);
}
question from:https://stackoverflow.com/questions/4066119/remove-items-from-list-1-not-in-list-2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
128 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can do this via RemoveAll using Contains:

list.RemoveAll( item => !list2.Contains(item));

Alternatively, if you just want the intersection, using Enumerable.Intersect would be more efficient:

list = list.Intersect(list2).ToList();

The difference is, in the latter case, you will not get duplicate entries. For example, if list2 contained 2, in the first case, you'd get {2,2,4,5}, in the second, you'd get {2,4,5}.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...