C# 中的 StringCollection 類


StringCollection 類表示字串的集合。以下是 StringCollection 類的屬性:

序號屬性及描述
1Count
獲取 OrderedDictionary 集合中包含的鍵/值對的數量。
2IsReadOnly
獲取一個值,該值指示 StringCollection 是否為只讀。
3IsSynchronized
獲取一個值,該值指示對 StringCollection 的訪問是否同步(執行緒安全)。
4Item[Int32]
獲取或設定指定索引處的元素。
5SyncRoot
獲取一個可用於同步對 StringCollection 訪問的物件。

以下是 StringCollection 類的使用方法:

序號方法及描述
1Add(String)
將字串新增到 StringCollection 的末尾。
2AddRange(String[])
將字串陣列的元素複製到 StringCollection 的末尾。
3Clear()
從 StringCollection 中刪除所有字串。
4Contains(String)
確定 StringCollection 中是否包含指定的字串。
5CopyTo(String[],Int32)
將整個 StringCollection 值複製到字串的一維陣列中,從目標陣列的指定索引開始。
6Equals(Object)
確定指定物件是否等於當前物件。(繼承自 Object)
7GetEnumerator()
返回一個 StringEnumerator,該列舉器迭代 StringCollection。

現在讓我們看一些例子

要檢查兩個 StringCollection 物件是否相等,程式碼如下:

示例

 線上演示

using System;
using System.Collections.Specialized;
public class Demo {
   public static void Main() {
      StringCollection strCol1 = new StringCollection();
      strCol1.Add("Accessories");
      strCol1.Add("Books");
      strCol1.Add("Electronics");
      Console.WriteLine("StringCollection1 elements...");
      foreach (string res in strCol1) {
         Console.WriteLine(res);
      }
      StringCollection strCol2 = new StringCollection();
      strCol2.Add("Accessories");
      strCol2.Add("Books");
      strCol2.Add("Electronics");
      Console.WriteLine("StringCollection2 elements...");
      foreach (string res in strCol1) {
         Console.WriteLine(res);
      }
      Console.WriteLine("Both the String Collections are equal? = "+strCol1.Equals(strCol2));
   }
}

輸出

這將產生以下輸出:

StringCollection1 elements...
Accessories
Books
Electronics
StringCollection2 elements...
Accessories
Books
Electronics
Both the String Collections are equal? = False

要檢查 StringCollection 中是否存在指定的字串,程式碼如下:

示例

 線上演示

using System;
using System.Collections.Specialized;
public class Demo {
   public static void Main() {
      StringCollection stringCol = new StringCollection();
      String[] arr = new String[] { "100", "200", "300", "400", "500" };
      Console.WriteLine("Array elements...");
      foreach (string res in arr) {
         Console.WriteLine(res);
      }
      stringCol.AddRange(arr);
      Console.WriteLine("Does the specified string is in the StringCollection? = "+stringCol.Contains("800"));
   }
}

輸出

這將產生以下輸出:

Array elements...
100
200
300
400
500
Does the specified string is in the StringCollection? = False

更新於:2019年12月10日

607 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告