C# SortedSet<T>
C# SortedSet<T>
C# SortedSet 类可用于存储、删除或查看元素。它保持升序并且不存储重复元素。如果您必须存储唯一元素并保持升序,建议使用 SortedSet 类。它位于 System.Collections.Generic 命名空间中。
C# SortedSet
示例
让我们看一个存储元素的通用 SortedSet
类的示例使用 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);
}
}
}
输出:
C# SortedSet
示例 2
让我们看另一个使用 Collection 初始值设定项存储元素的通用 SortedSet
类示例。
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);
}
}
}
输出: