将List <int>转换为List <int?>的最快方法

use*_*544 20 c# linq performance

获取原始列表并将其转换为可为空的基元列表的最快方法是什么,例如:List<int>to List<int?>in c#

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

Moh*_*han 44

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

var newList = list.Select( i => (int?)i ).ToList();
Run Code Online (Sandbox Code Playgroud)

但是使用LINQ比使用裸循环要慢.

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

List<int?> newList = new List<int?>(list.Count); // Allocate enough memory for all items
foreach (var i in list)
    newList.Add(i);
Run Code Online (Sandbox Code Playgroud)

如果您正在寻找列表项的就地类型转换,那是不可能的.

  • @Fuex有趣.我的测试还表明,裸环比LINQ(包含1,000,000个)项目快30%-40%. (3认同)

Mat*_*ten 13

而不是Select你可以坚持CastLINQ运营商:

List<int> first = new List<int>() {1, 2, 3};
List<int?> second = first.Cast<int?>().ToList();
Run Code Online (Sandbox Code Playgroud)

  • 你能证明这一点吗? (2认同)

Oma*_*mar 7

如果你想知道什么是更快的解决方案,你应该通过三种不同的方式做一点基准测试:

List<int> list = Enumerable.Range( 0, 10000 ).ToList( );
Stopwatch sw = Stopwatch.StartNew( );

for ( int i = 0; i < 100000; i++ ) {
   List<int?> newList = new List<int?>( );
   foreach( int integer in list )
      newList.Add( ( int? ) integer );
}

sw.Stop( );
TimeSpan timespan = sw.Elapsed;
Console.WriteLine( String.Format( "Foreach: {0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds / 10 ) );
sw.Restart( );

for ( int i = 0; i < 100000; i++ ){
   List<int?> newList = list.Select( x => ( int? ) x ).ToList( );
}

sw.Stop( );
timespan = sw.Elapsed;
Console.WriteLine( String.Format( "LINQ-Select: {0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds / 10 ) );
sw.Restart( );

for ( int i = 0; i < 100000; i++ ){
   List<int?> newList = list.Cast<int?>( ).ToList( );
}

sw.Stop();
timespan = sw.Elapsed;
Console.WriteLine( String.Format( "LINQ-Cast: {0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds / 10 ) );
Run Code Online (Sandbox Code Playgroud)

结果:

基准

我们可以期待最好的方法是第一个解决方案(foreach),这意味着循环遍历元素,强制转换并将它们添加到新列表中.