C#のコレクションに含まれる要素の数を取得します
コレクションに含まれる要素の数を取得するためのコードは次のとおりです-
例
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
例
別の例を見てみましょう-
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
-
要素がC#のコレクションにあるかどうかを確認します
要素がコレクションにあるかどうかを確認するためのコードは、次のとおりです- 例 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); &n
-
C#リストの要素の範囲を取得する
GetRange()メソッドを使用して、要素の範囲を取得します- まず、リストを設定して要素を追加します- List<int> arr1 = new List<int>(); arr1.Add(10); arr1.Add(20); arr1.Add(30); arr1.Add(40); arr1.Add(50); ここで、新しいリストの下で、インデックス1と3の間の要素の範囲を取得します- List<int> myList = arr1.GetRange(1, 3); これが完全なコードです- 例 using System; using System.