简体   繁体   中英

c# - What would be more effective to remove null values from a list?

I want to remove all null values from a List in C# and i wonder what would be more effective and why?

Option #1:

myList.RemoveAll(item => item == null);

Option #2:

myList = myList.Where(x => x != null).ToList();

Thank you!

The two approaches are very different in their semantics:

  • The first approach is "destructive," in the sense that myList is changed, while
  • The second approach is "non-destructive," as a new List is created. Your code also discards the original, but it does not need to do so.

Both ways of removing elements have O(n) time complexity. The second way requires creation of a new List , while the first way may require copying of the "tail" of the list. Overall, you should see reasonably similar performance when the number of items you keep is similar to the number of items you discard.

One situation when the first approach is a clear winner is when all items are non-null, in which case the method performs no copying or re-allocations. If you expect the search for null be unsuccessful most of the time, use the first approach.

I would say the first. Mainly because of 2 reasons.

  1. It's more easily to read.
  2. You don't have to call .ToList() . Basically, you are creating a new list, which costs a lot of resoures.

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