C# 中的 StringCollection 类
StringCollection 类表示字符串的集合。以下是 StringCollection 类的属性:
| 序号 | 属性及描述 |
|---|---|
| 1 | Count 获取 OrderedDictionary 集合中包含的键/值对的数量。 |
| 2 | IsReadOnly 获取一个值,该值指示 StringCollection 是否为只读。 |
| 3 | IsSynchronized 获取一个值,该值指示对 StringCollection 的访问是否同步(线程安全)。 |
| 4 | Item[Int32] 获取或设置指定索引处的元素。 |
| 5 | SyncRoot 获取一个可用于同步对 StringCollection 访问的对象。 |
以下是 StringCollection 类的使用方法:
| 序号 | 方法及描述 |
|---|---|
| 1 | Add(String) 将字符串添加到 StringCollection 的末尾。 |
| 2 | AddRange(String[]) 将字符串数组的元素复制到 StringCollection 的末尾。 |
| 3 | Clear() 从 StringCollection 中删除所有字符串。 |
| 4 | Contains(String) 确定 StringCollection 中是否包含指定的字符串。 |
| 5 | CopyTo(String[],Int32) 将整个 StringCollection 值复制到字符串的一维数组中,从目标数组的指定索引开始。 |
| 6 | Equals(Object) 确定指定对象是否等于当前对象。(继承自 Object) |
| 7 | GetEnumerator() 返回一个 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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP