简体   繁体   中英

Remove elements from one List<T> that are found in another

I have two lists

 List<T> list1 = new List<T>();
 List<T> list2 = new List<T>();

I want remove all elements from list1, which also exist in list2. Of course I can loop through the first loop looking for each element in list2, but I am looking for elegant solution.

Thanks!

To change the actual list1 in place, you could use

list1.RemoveAll(item => list2.Contains(item));

You might instead prefer to simply have a query over the lists without modifying either

var result = list1.Except(list2);

LukeH makes a good recommendation in the comments. In the first version, and if list2 is particularly large, it might be worth it to load the list into a HashSet<T> prior to the RemoveAll invocation. If the list is small, don't worry about it. If you are unsure, test both ways and then you will know.

var theSet = new HashSet<YourType>(list2);
list1.RemoveAll(item => theSet.Contains(item));

使用LINQ:

var result = list1.Except(list2);
list1.RemoveAll( item => list2.Contains(item));

Description

I think you mean the generic type List<Type> . You can use Linq to do this

Sample

List<string> l = new List<string>();
List<string> l2 = new List<string>();

l.Add("one");
l.Add("two");
l.Add("three");

l2.Add("one");
l2.Add("two");
l2.Add("three");
l2.Add("four");

l2.RemoveAll(x => l.Contains(x));

More Information

var result = list1.Except(list2);

使用LINQ,您可以执行以下操作:

 List1.RemoveAll(i => !List2.Contains(i));

If you want to remove a list of objects ( list2 ) from another list ( list1 ) use:

list1 = list1.Except(list2).ToList()

Remember to use ToList() to convert IEnumerable<T> to List<T> .

        var NewList = FirstList.Where(a => SecondList.Exists(b => b.ID != a.ID));

使用LINQ

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM