简体   繁体   中英

Linq: how can I speed up the string comparison inside for a RemoveAll predicate?

List<string> listToTemove
list.ForEach(e => e.Persons.RemoveAll(m => listToTemove.Any(m1 => m1 == m.Name)));

Persons is a List<Person> and Person has a property Name

The operation lasts 70 seconds. The list has 30 elements each of which has a list of 400 elements for a total of 21000 string comparisons.

Most of Persons are removed..

Instead of having it as a List<string> use a HashSet<string> :

HashSet<string> itemsToRemove = new HashSet<string>(listToTemove);
e.Persons.RemoveAll(m => itemsToRemove.Contains(m.Name));

A single Contains on HashSet is an O(1) operation whereas on a List it is O(n) . Lowering the total of an O(n^2) to O(n) .

Also instead of removing you can maybe select only those you want:

e.Persons = e.Persons.Where(m => itemsToRemove.Contains(m.Name)).ToList();

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