What is the fastest way of taking a list of primitives and converting it to a nullable list of primitives? For example: List<int>
to List<int?>
.
The easy solution, creating a new list and adding every item with a foreach
loop, takes too much time.
Use int() function to Convert list to int in Python. This method with a list comprehension returns one integer value that combines all elements of the list.
The recommended approach to convert a list of one type to another type is using the List<T>. ConvertAll() method. It returns a list of the target type containing the converted elements from the current list.
There is no way faster than creating a new list:
var newList = list.Select( i => (int?)i ).ToList();
However using LINQ is slower than using a bare loop.
The fastest way is to use a List<int?>
with pre-allocated capacity:
List<int?> newList = new List<int?>(list.Count); // Allocate enough memory for all items foreach (var i in list) newList.Add(i);
If you are seeking for in-place type change of list items, it's not possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With