在 C# 中檢查兩個 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

示例

讓我們看另一個示例 −

 即時演示

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));
      StringCollection strCol3 = new StringCollection();
      strCol3 = strCol2;
      Console.WriteLine("Is StringCollection3 equal to StringCollection2? = "+strCol3.Equals(strCol2));
   }
}

輸出

這將產生以下輸出 −

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

更新於:05-Dec-2019

86 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告