Remove items from list 1 not in list 2

后端 未结 4 1304
我在风中等你
我在风中等你 2021-02-01 14:32

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

        
4条回答
  •  孤城傲影
    2021-02-01 15:03

    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}.

提交回复
热议问题