C#でコレクションに含まれる要素の数を取得する方法(Countプロパティ)
C#の Collection<T> クラスに格納されている要素の数を取得するには、Count プロパティを使用します。このプロパティは、コレクション内に現在存在する実際の要素数を int 型で返します。
Countプロパティの基本構文
int elementCount = collection.Count;
Count プロパティは内部的に要素数をキャッシュしているため、呼び出しにかかる計算量は O(1) と非常に高速です。ループの中で何度参照してもパフォーマンスへの影響はほとんどありません。
例1:文字列のコレクションで要素数を取得する
以下は、文字列型のコレクションに要素を追加し、その要素数を取得するサンプルコードです。
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main() {
Collection<string> col = new Collection<string>();
col.Add("Andy");
col.Add("Kevin");
col.Add("John");
col.Add("Kevin");
col.Add("Mary");
col.Add("Katie");
col.Add("Barry");
col.Add("Nathan");
col.Add("Mark");
Console.WriteLine("Count of elements = " + col.Count);
Console.WriteLine("Iterating through the collection...");
var enumerator = col.GetEnumerator();
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
}
}実行結果
上記のコードを実行すると、次のような出力が得られます。
Count of elements = 9 Iterating through the collection... Andy Kevin John Kevin Mary Katie Barry Nathan Mark
9つの要素を追加したため、col.Count は「9」を返しています。なお、重複する値(この例では「Kevin」が2回)も1つずつカウントされる点に注意してください。
例2:数値のコレクションで要素数を取得・更新する
次に、整数型のコレクションを使い、要素の確認、要素数の取得、そして Clear() メソッドによる全削除後の要素数の変化を見てみましょう。
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main() {
Collection<int> col = new Collection<int>();
col.Add(10);
col.Add(20);
col.Add(30);
col.Add(40);
col.Add(50);
col.Add(60);
col.Add(70);
col.Add(80);
Console.WriteLine("Elements in the Collection...");
foreach(int val in col) {
Console.WriteLine(val);
}
Console.WriteLine("Does the collection has the element 70? = " + col.Contains(70));
Console.WriteLine("Count of elements = " + col.Count);
col.Clear();
Console.WriteLine("Count of elements (updated) = " + col.Count);
}
}実行結果
上記のコードを実行すると、次のような出力が得られます。
Elements in the Collection... 10 20 30 40 50 60 70 80 Does the collection has the element 70? = True Count of elements = 8 Count of elements (updated) = 0
8つの要素を追加した直後は Count が「8」を返しますが、Clear() を呼び出してすべての要素を削除すると、「0」に更新されます。このように、Count プロパティは常にコレクションの最新の状態を反映します。
まとめ
Collection<T>の要素数を取得するにはCountプロパティを使う。- Count は実際に格納されている要素数を返すため、追加・削除のたびに自動的に更新される。
- 配列の
Lengthとは異なり、リスト系コレクションではCountを使用する点に注意。
-
C#のCollectionに要素が含まれているかどうかを確認する方法
C#でコレクション(Collection)内に特定の要素が存在するかどうかを確認するには、Contains()メソッドを使用します。このメソッドは、指定した要素がコレクション内に見つかった場合は true、見つからなかった場合は false を返します。以下に具体的なコード例を示します。例1:整数のコレクションの場合using System; using System.Collections.ObjectModel; public class Demo { public static void Main(){  
-
C#でListの要素範囲を取得する方法:GetRange()メソッドの使い方
C#のListで特定の範囲の要素を取得するには、GetRange() メソッドを使用します。このメソッドは、指定したインデックス位置から指定した数の要素を取り出し、新しいリストとして返します。 GetRange() メソッドの基本構文 public List<T> GetRange(int index, int count); index:取得を開始する要素のインデックス(0から始まります) count:取得する要素の数 リストの作成と要素の追加 まず、リストを作成して要素を追加します。 List<int> arr1 = new List<int>();