リストの長さ、サイズを取得する方法を紹介します。
1. List.Countにリスト長を取得する
List.Add()
は要素をリストに追加します。
要素が追加されるたびにリストの長さは増加しますが、List.Count
でリストの長さを取得できます。
using System;
namespace Example {
public class Program {
public static void Main(string[] args) {
List<string> list = new List<string>();
list.Add("A");
list.Add("B");
list.Add("C");
Console.WriteLine(list.Count);
list.Add("D");
list.Add("E");
Console.WriteLine(list.Count);
}
}
}
Output:
3
5
2. for文とCountでリスト巡回
以下のようにfor文とCountでリストのすべての要素を巡回できます。
List.ElementAt(index)
はリストから index の要素を返します。
using System;
namespace Example {
public class Program {
public static void Main(string[] args) {
List<string> list = new List<string>();
list.Add("A");
list.Add("B");
list.Add("C");
list.Add("D");
list.Add("E");
for (int i = 0; i < list.Count; i++) {
Console.WriteLine(list.ElementAt(i));
}
}
}
}
Output:
A
B
C
D
E
Related Posts
- C# - Dictionaryからkey、valueを取得する
- C# - Dictionary 巡回, foreach, for ループ
- C# - Dictionaryからkey、valueを削除する
- C# - Dictionary.add()でデータを追加する
- C# - Dictionary宣言と初期化
- C# - 文字列をDouble、Floatに変換
- C# - 文字列をリストに変換
- C# - 日付計算、DateTime時間プラス減算
- C# - 日付文字列をDateTimeに変換
- C# - 2つの日付/時刻比較、DateTime.Compare()
- C# - Sleep、数秒間遅らせる
- C# - TimestampをDateTimeオブジェクトに変換する
- C# - 現在時刻を取得する、DateTime
- C# - 文字列リストを文字列に変換
- C# - リストコピー(浅いコピー、深いコピー)
- C# - 2次元リスト宣言と初期化
- C# - リスト宣言と初期化
- C# - リストの長さ、サイズを取得する
- C# - リスト合計、平均計算
- C# - リスト要素を削除する(RemoveAt、RemoveAt、RemoveAll)
- C# - リストから空の文字列、nullを削除する