コレクション

[C#] List型の要素を一括で型変換する(.ConvertAll)

2021年5月29日

List型の要素を一括で型変換したい場合は、.ConvertAll()を使うと簡単です。

サンプル

例)List<string>の要素を全てintに変換する

using System;
using System.Collections.Generic;

//stringのList
List<string> listStr = new List<string>() {"1", "2", "3", "4", "5"};

//intのListに変換する
List<int> listInt = listStr.ConvertAll(x => int.Parse(x));

備考

  • 要素の中に1つでも変換できない値があると、例外「System.FormatException」が発生します。

関連記事

-コレクション