C#
 Computer >> コンピューター >  >> プログラミング >> C#

C#のコレクションで指定されたインデックスの要素を取得または設定します


コレクション内の指定されたインデックスで要素を取得または設定するには、コードは次のとおりです-

using System;
using System.Collections.ObjectModel;
public class Demo {
   public static void Main() {
      Collection<string> col = new Collection<string>();
      col.Add("Laptop");
      col.Add("Desktop");
      col.Add("Notebook");
      col.Add("Ultrabook");
      col.Add("Tablet");
      col.Add("Headphone");
      col.Add("Speaker");
      Console.WriteLine("Elements in Collection...");
      foreach(string str in col) {
         Console.WriteLine(str);
      }
      Console.WriteLine("Element at index 3 = " + col[3]);
      Console.WriteLine("Element at index 4 = " + col[4]);
   }
}

出力

これにより、次の出力が生成されます-

Elements in Collection...
Laptop
Desktop
Notebook
Ultrabook
Tablet
Headphone
Speaker
Element at index 3 = Ultrabook
Element at index 4 = Tablet

別の例を見てみましょう-

using System;
using System.Collections.ObjectModel;
public class Demo {
   public static void Main() {
      Collection<string> col = new Collection<string>();
      col.Add("Laptop");
      col.Add("Desktop");
      col.Add("Notebook");
      col.Add("Ultrabook");
      col.Add("Tablet");
      col.Add("Headphone");
      col.Add("Speaker");
      Console.WriteLine("Elements in Collection...");
      foreach(string str in col) {
         Console.WriteLine(str);
      }
      Console.WriteLine("Element at index 3 = " + col[3]);
      col[3] = "SSD";
      Console.WriteLine("Element at index 3 (Updated) = " + col[3]);
   }
}

出力

これにより、次の出力が生成されます-

Elements in Collection...
Laptop
Desktop
Notebook
Ultrabook
Tablet
Headphone
Speaker
Element at index 3 = Ultrabook
Element at index 3 (Updated) = SSD

  1. 要素が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

  2. HashSetにC#で指定された要素が含まれているかどうかを確認します

    HashSetに指定された要素が含まれているかどうかを確認するためのコードは、次のとおりです- 例 using System; using System.Collections.Generic; public class Demo {    public static void Main(){       HashSet<int> set1 = new HashSet<int>();       set1.Add(25);       set1.Add(50);