C#中的StringCollection类
StringCollection类表示字符串的集合。以下是StringCollection类的属性-
获取OrderedDictionary集合中包含的键/值对的数量。
获取一个值,该值指示StringCollection是否为只读。
获取一个值,该值指示是否同步对StringCollection的访问(线程安全)。
获取或设置指定索引处的元素。
获取一个对象,该对象可用于同步对StringCollection的访问。
以下是StringCollection类的方法-
将一个字符串添加到StringCollection的末尾。
将字符串数组的元素复制到StringCollection的末尾。
从StringCollection中删除所有字符串。
确定指定的字符串是否在StringCollection中。
从目标数组的指定索引处开始,将整个StringCollection值复制到一维字符串数组。
确定指定的对象是否等于当前的对象。(继承自Object)
返回一个通过StringCollection进行迭代的StringEnumerator。
现在让我们来看一些例子
要检查两个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("数组元素...-"); foreach (string res in arr) { Console.WriteLine(res); } stringCol.AddRange(arr); Console.WriteLine("Does the specified string is in the StringCollection? = "+stringCol.Contains("800")); } }
输出结果
这将产生以下输出-
数组元素...- 100 200 300 400 500 Does the specified string is in the StringCollection? = False