LoginSignup
33
29

More than 5 years have passed since last update.

IEnumerable<T> を List<T>に変換するには .ToList() を使う

Posted at

ちょっとつまづいたのでメモ。

C# の LINQ to Objects は、var で結果を受け取る限り、普段は変数の型をそれほど意識する必要はないのですが、メソッドの返り値として渡そうとしたところ、型が違うために以下のエラーが発生しました。

型 'System.Collections.Generic.IEnumerable<string>' を'System.Collections.Generic.List<string>' に暗黙的に変換できません。明示的な変換が存在します。(cast が不足していないかどうかを確認してください) (CS0266)

解決方法

.ToList()メソッドで、 IEnumerable 型から List 型に変換することで解決。

sample_linq_tolist.cs
public static List<string> GetFileListWildcardExpanded(List<string> OriginalFileList)
{
    var newFileList = new List<string>();

    // (中略)

    // Distinct - 重複削除
    //return newFileList.Distinct();    // (CS0266)
    return newFileList.Distinct().ToList();
}
33
29
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
29