Home > Enterprise >  Remove items from List<T> where condition [closed]
Remove items from List<T> where condition [closed]

Time:09-17

I got a List<Person> listA -> where Person has

string name
int age
List<string> jobs

I need to remove from listA all items that jobs.count() < 1, using linq, any ideas?

CodePudding user response:

You shouldn't mutate a list using LINQ, because it's designed for querying, however, List<T> already has a RemoveAll method as part of it's protocol:

listA.RemoveAll(person => person.Jobs.Count < 1);

RemoveAll accepts a Predicate<T> delegate which should return true when an item is to be removed.

However, if you're intention is to create a new list that only contains people with less than one job, you can use LINQ:

var newList = listA
    .Where(person => person.Jobs.Count < 1)
    .ToList();
  • Related