C#SortedSet类可用于存储、删除或查看元素。它保持升序,不存储重复元素。如果必须存储唯一元素并保持升序,建议使用SortedSet类。它位于System.Collections.Generic命名空间中。
让无涯教程看一个泛型SortedSet<T>类的示例,该类使用add()方法存储元素,并使用for-each循环迭代元素。
using System; using System.Collections.Generic; public class SortedSetExample { public static void Main(string[] args) { // Create a set of strings var names = new SortedSet(); names.Add("Sonoo"); names.Add("Ankit"); names.Add("Peter"); names.Add("Irfan"); names.Add("Ankit");//will not be added // 使用 foreach 循环迭代 SortedSet 元素 foreach (var name in names) { Console.WriteLine(name); } } }
输出:
Ankit Irfan Peter Sonoo
让无涯教程看一下使用集合初始值设定项存储元素的泛型SortedSet<T>类的另一个示例。
using System; using System.Collections.Generic; public class SortedSetExample { public static void Main(string[] args) { // Create a set of strings var names = new SortedSet(){"Sonoo", "Ankit", "Peter", "Irfan"}; // Iterate SortedSet elements using foreach loop foreach (var name in names) { Console.WriteLine(name); } } }
输出:
Ankit Irfan Peter Sonoo
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)