Using LINQ to remove elements from a List

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Using LINQ to remove elements from a List

Message par ForumBot »

Using LINQ to remove elements from a List
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Using LINQ to remove elements from a List

Message par ForumBot »

Well, it would be easier to exclude them in the first place:

```
authorsList = authorsList.Where(x => x.FirstName != "Bob").ToList();

```

However, that would just change the value of `authorsList` instead of removing the authors from the previous collection. Alternatively, you can use [`RemoveAll`](http://msdn.microsoft.com/en-us/library/wdka673a.aspx):

```
authorsList.RemoveAll(x => x.FirstName == "Bob");

```

If you really need to do it based on another collection, I'd use a HashSet, RemoveAll and Contains:

```
var setToRemove = new HashSet(authors);
authorsList.RemoveAll(x => setToRemove.Contains(x));

```
Répondre

Revenir à « .NET & C# »