转换List< int>的最快方法列出< int?> [英] Fastest way to convert List<int> to List<int?>

查看:82
本文介绍了转换List< int>的最快方法列出< int?>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最快的方法是获取原始列表并将其转换为可为空的原始列表 例如:在c#

What is the fastest way take list of primitivtes and convert it to nullable list of primitives for example: List<int> to List<int?> in c#

简单的解决方案,创建新列表以及使用foreach循环添加每个项目都需要太多时间.

the easy solution, creating new list and adding every item with foreach loop takes too much time.

推荐答案

没有比创建新列表更快的方法:

There is no way faster than creating a new list:

var newList = list.Select( i => (int?)i ).ToList();

但是,使用LINQ的速度比使用裸露循环的速度慢.

However using LINQ is slower that using a bare loop.

最快的方法是使用具有预分配容量的List<int?>:

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 casting of list items, it's not possible.

这篇关于转换List&lt; int&gt;的最快方法列出&lt; int?&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆