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:
myList
is changed, while 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.
.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.