プリミティブのリストを取得し、それをnull許容のプリミティブのリストに変換する最速の方法は何ですか?例:List<int>
to List<int?>
。
新しいリストを作成し、ループを使用してすべてのアイテムを追加するという簡単な解決策はforeach
、時間がかかりすぎます。
プリミティブのリストを取得し、それをnull許容のプリミティブのリストに変換する最速の方法は何ですか?例:List<int>
to List<int?>
。
新しいリストを作成し、ループを使用してすべてのアイテムを追加するという簡単な解決策はforeach
、時間がかかりすぎます。
新しいリストを作成するよりも速い方法はありません。
var newList = list.Select( i => (int?)i ).ToList();
ただし、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);
リストアイテムのインプレースタイプ変更を探している場合、それは不可能です。
代わりに、 LINQ-operatorSelect
に固執することができます。Cast
List<int> first = new List<int>() {1, 2, 3};
List<int?> second = first.Cast<int?>().ToList();
より高速なソリューションを知りたい場合は、次の 3 つの方法を使用して少しベンチマークを行う必要があります。
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 ) );
結果:
最善の方法は最初の解決策 ( foreach
) です。これは要素をループし、キャストして新しいリストに追加することを意味します。