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<string>(); names.Add("Sonoo"); names.Add("Ankit"); names.Add("Peter"); names.Add("Irfan"); names.Add("Ankit");//will not be added // Iterate SortedSet elements using foreach loop foreach (var name in names) { Console.WriteLine(name); } } }
输出:
Ankit Irfan Peter Sonoo
让我们看看另一个使用 Collection 初始化器存储元素的通用 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<string>(){"Sonoo", "Ankit", "Peter", "Irfan"}; // Iterate SortedSet elements using foreach loop foreach (var name in names) { Console.WriteLine(name); } } }
输出:
Ankit Irfan Peter Sonoo