C#のリストで指定されたインデックスにある要素を取得または設定します
リスト内の指定されたインデックスを使用して要素を取得または設定するには、コードは次のとおりです-
例
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args) {
List<String> list = new List<String>();
list.Add("100");
list.Add("200");
list.Add("300");
list.Add("400");
list.Add("500");
list.Add("600");
list.Add("700");
list.Add("800");
list.Add("900");
list.Add("1000");
Console.WriteLine("Element at index 0 = " + list[0]);
Console.WriteLine("Element at index 1 = " + list[1]);
Console.WriteLine("Element at index 2 = " + list[2]);
Console.WriteLine("Element at index 3 = " + list[3]);
Console.WriteLine("Element at index 4 = " + list[4]);
Console.WriteLine("Element at index 5 = " + list[5]);
Console.WriteLine("Element at index 6 = " + list[6]);
Console.WriteLine("Element at index 7 = " + list[7]);
}
} 出力
これにより、次の出力が生成されます-
Element at index 0 = 100 Element at index 1 = 200 Element at index 2 = 300 Element at index 3 = 400 Element at index 4 = 500 Element at index 5 = 600 Element at index 6 = 700 Element at index 7 = 800
例
別の例を見てみましょう-
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args) {
List<String> list = new List<String>();
list.Add("100");
list.Add("200");
list.Add("300");
list.Add("400");
list.Add("500");
list.Add("600");
list.Add("700");
list.Add("800");
list.Add("900");
list.Add("1000");
Console.WriteLine("Element at index 0 = " + list[0]);
Console.WriteLine("Element at index 1 = " + list[1]);
Console.WriteLine("Element at index 2 = " + list[2]);
Console.WriteLine("Element at index 3 = " + list[3]);
Console.WriteLine("Element at index 4 = " + list[4]);
Console.WriteLine("Element at index 5 = " + list[5]);
Console.WriteLine("Element at index 6 = " + list[6]);
Console.WriteLine("Element at index 7 = " + list[7]);
list[3] = "450";
Console.WriteLine("Element at index 3 [UPDATED] = " + list[3]);
}
} 出力
これにより、次の出力が生成されます-
Element at index 0 = 100 Element at index 1 = 200 Element at index 2 = 300 Element at index 3 = 400 Element at index 4 = 500 Element at index 5 = 600 Element at index 6 = 700 Element at index 7 = 800 Element at index 3 [UPDATED] = 450
-
Pythonでリストの最後の要素を取得するにはどうすればよいですか?
リストオブジェクトを含むPythonシーケンスにより、インデックスを作成できます。リスト内の任意の要素には、ゼロベースのインデックスを使用してアクセスできます。インデックスが負の数の場合、インデックスのカウントは最後から始まります。リストの最後の要素が必要なので、インデックスとして-1を使用します。 >>> L1=[1,2,3,4,5] >>> print (L1[-1]) 5
-
Pythonでリスト内の要素のインデックスを見つける方法は?
List(および文字列やタプルなどの他のシーケンスタイプ)で使用できるindex()メソッドは、その中の特定の要素の最初の出現を見つけるのに役立ちます。 >>> L1=['a', 'b', 'c', 'a', 'x'] >>> L1 ['a', 'b', 'c', 'a', 'x'] >>> L1.index('a') 0 要素のすべての出現箇所のインデックスを取得す