Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to convert List<int> to List<int?>

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.

like image 271
user1039544 Avatar asked Mar 03 '13 10:03

user1039544


People also ask

How to convert list to integers in Python?

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.

How to convert list types c#?

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.


1 Answers

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.

like image 147
Mohammad Dehghan Avatar answered Sep 17 '22 13:09

Mohammad Dehghan