Any easy way to cast List<int?> to List<int>

.net, c#

Solution

The built-in way to convert each element in one `List<T1>` and store the result in another `List<T2>` is `List<T1>.ConvertAll`.

List<int> ints = tuple.Item2.ConvertAll(s => s.Value);

Unlike `.Select(...).ToList()` or `.Cast(...).ToList()`, this method knows the list size in advance, and prevents unnecessary reallocations that `.ToList()` cannot avoid.

For this to work, `tuple.Item2` must really be a `List<int?>`. It's not an extension method, it cannot work on the generic `IEnumerable<int?>` interface.

Problem

At the moment I use `List<int> ints = tuple.Item2.Select(s => s.Value).ToList()` but this looks inefficient when tuple.Item2 has 1000's of items. Any better way to achieve this? except using a for loop.

Original source

Related problems