C#のListを反復処理する列挙子(Enumerator)を取得する方法
C#でList<T>を反復処理するための列挙子(Enumerator)を取得するには、GetEnumerator()メソッドを使用します。このメソッドは、リスト内の各要素に順番にアクセスできるList<T>.Enumerator構造体を返します。
基本的な使い方
取得した列挙子は、MoveNext()メソッドで次の要素へ進み、Currentプロパティで現在の要素を取得します。以下のコード例を見てみましょう。
コード例
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args){
List<String> list1 = new List<String>();
list1.Add("One");
list1.Add("Two");
list1.Add("Three");
list1.Add("Four");
list1.Add("Five");
Console.WriteLine("List1の要素...");
foreach (string res in list1){
Console.WriteLine(res);
}
List<String> list2 = new List<String>();
list2.Add("India");
list2.Add("US");
list2.Add("UK");
list2.Add("Canada");
list2.Add("Poland");
list2.Add("Netherlands");
Console.WriteLine("List2の要素...");
List<String>.Enumerator demoEnum = list2.GetEnumerator();
while (demoEnum.MoveNext()) {
string res = demoEnum.Current;
Console.WriteLine(res);
}
Console.WriteLine("List2はList1と等しいか? = "+list2.Equals(list1));
}
}出力結果
List1の要素... One Two Three Four Five List2の要素... India US UK Canada Poland Netherlands List2はList1と等しいか? = False
コードの解説
上記の例では、まずforeachループを使ってlist1の全要素を表示しています。続いて、list2に対してGetEnumerator()メソッドを呼び出し、返された列挙子をwhileループで反復処理しています。MoveNext()がtrueを返す間、Currentプロパティから現在の要素を取り出してコンソールに出力します。最後に、Equals()メソッドで2つのリストが等しいかどうかを比較し、その結果を表示しています。
別の例
もう一つ例を挙げます。10個の文字列要素を持つリストを、列挙子を使って先頭から順に反復処理してみましょう。
コード例
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args){
List<String> list = new List<String>();
list.Add("One");
list.Add("Two");
list.Add("Three");
list.Add("Four");
list.Add("Five");
list.Add("Six");
list.Add("Seven");
list.Add("Eight");
list.Add("Nine");
list.Add("Ten");
Console.WriteLine("列挙子によるリスト要素の反復処理...");
List<String>.Enumerator demoEnum = list.GetEnumerator();
while (demoEnum.MoveNext()) {
string res = demoEnum.Current;
Console.WriteLine(res);
}
}
}出力結果
列挙子によるリスト要素の反復処理... One Two Three Four Five Six Seven Eight Nine Ten
ポイントまとめ
GetEnumerator()は、List<T>専用の列挙子であるList<T>.Enumerator構造体を返します。MoveNext()メソッドは、次の要素が存在すればtrueを返し、列挙子の位置を前へ進めます。Currentプロパティは、現在の位置にある要素を返します。foreachループは内部でこの列挙子を利用しているため、単純な反復処理であればforeachを使う方が簡潔に書けます。
-
C#でListの要素範囲を取得する方法:GetRange()メソッドの使い方
C#のListで特定の範囲の要素を取得するには、GetRange() メソッドを使用します。このメソッドは、指定したインデックス位置から指定した数の要素を取り出し、新しいリストとして返します。 GetRange() メソッドの基本構文 public List<T> GetRange(int index, int count); index:取得を開始する要素のインデックス(0から始まります) count:取得する要素の数 リストの作成と要素の追加 まず、リストを作成して要素を追加します。 List<int> arr1 = new List<int>();
-
【C#】Dictionaryからキーのリストを取得する方法
C#では、Dictionary<TKey, TValue> に格納されたすべてのキーを、List<TKey> として簡単に取り出すことができます。この記事では、Keys プロパティを使ってキーの一覧をリスト化し、画面に表示するまでの手順をサンプルコード付きで解説します。 Dictionaryに要素を追加する まずは、辞書(Dictionary)に要素を設定しましょう。 Dictionary<int, string> d = new Dictionary<int, string>(); // 辞書の要素 d.Add(1, "One&q