C# でリストを IEnumerable に変換する
-
C# で
as
キーワードを使用してリストを IEnumerable に変換する - C# の型キャストメソッドを使用してリストを IEnumerable に変換する
- C# の LINQ メソッドを使用してリストを IEnumerable に変換する

このチュートリアルでは、C# でリストを IEnumerable
に変換する方法について説明します。
C# で as
キーワードを使用してリストを IEnumerable に変換する
C# の as
キーワードを使用して、List
データ構造を IEnumerable
データ構造に変換できます。次の例を参照してください。
using System;
using System.Collections.Generic;
namespace list_to_ienumerable
{
class Program
{
static void Main(string[] args)
{
List<int> ilist = new List<int> { 1, 2, 3, 4, 5 };
IEnumerable<int> enumerable = ilist as IEnumerable<int>;
foreach (var e in enumerable)
{
Console.WriteLine(e);
}
}
}
}
出力:
1
2
3
4
5
上記のコードでは、C# の as
キーワードを使用して、整数 ilist
のリスト
を整数 enumerable
の IEnumerable
に変換しました。
C# の型キャストメソッドを使用してリストを IEnumerable に変換する
次のコード例に示すように、型キャストメソッドを使用して、List
データ型のオブジェクトを IEnumerable
データ型のオブジェクトに格納することもできます。
using System;
using System.Collections.Generic;
namespace list_to_ienumerable
{
class Program
{
static void Main(string[] args)
{
List<int> ilist = new List<int> { 1, 2, 3, 4, 5 };
IEnumerable<int> enumerable = (IEnumerable<int>)ilist;
foreach (var e in enumerable)
{
Console.WriteLine(e);
}
}
}
}
出力:
1
2
3
4
5
上記のコードでは、C# の型キャストメソッドを使用して、整数 ilist
の List
を整数 enumerable
の IEnumerable
に変換しました。
C# の LINQ メソッドを使用してリストを IEnumerable に変換する
LINQ は、SQL クエリ機能を C# のデータ構造と統合します。LINQ の AsEnumerable()
関数を使用して、C# でリストを IEnumerable
に変換できます。次のコード例は、C# で LINQ の AsEnumerable()
関数を使用して、List
データ構造を IEnumerable
データ構造に変換する方法を示しています。
using System;
using System.Collections.Generic;
using System.Linq;
namespace list_to_ienumerable
{
class Program
{
static void Main(string[] args)
{
List<int> ilist = new List<int> { 1, 2, 3, 4, 5 };
IEnumerable<int> enumerable = ilist.AsEnumerable();
foreach (var e in enumerable)
{
Console.WriteLine(e);
}
}
}
}
出力:
1
2
3
4
5
上記のコードでは、C# の ilist.AsEnumerable()
関数を使用して、整数 ilist
の List
を整数 enumerable
の IEnumerable
に変換しました。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn関連記事 - Csharp List
- C# で列挙をリストに変換する方法
- C# でリストからアイテムを削除
- C#2つのリストを結合する
- C# のフィールドでリストを並べ替える
- C# で辞書をリストコレクションに変換する
- C# の HashSet とリスト