📅  最后修改于: 2023-12-03 15:14:27.495000             🧑  作者: Mango
The C# SortedSet class is a collection class in the .NET framework that represents a sorted set of elements that may not contain duplicate entries. It is implemented as a binary search tree and provides efficient searching, inserting, and deleting operations.
The SortedSet class is declared in the System.Collections.Generic namespace as follows:
public class SortedSet<T> : ICollection<T>, IEnumerable<T>, IEnumerable, IReadOnlyCollection<T>
Here, T is the type of elements in the set.
The SortedSet class provides several constructors, allowing you to create a new sorted set:
public SortedSet();
public SortedSet(IEnumerable<T> collection);
public SortedSet(IComparer<T> comparer);
public SortedSet(IEnumerable<T> collection, IComparer<T> comparer);
public SortedSet(SerializationInfo info, StreamingContext context);
The SortedSet class provides the following properties:
The SortedSet class provides the following methods:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
SortedSet<string> set = new SortedSet<string>(new[]{"apple", "banana", "orange"});
set.Add("pear");
foreach (string fruit in set)
{
Console.WriteLine(fruit);
}
}
}
Output:
apple
banana
orange
pear
In this example, we created a new sorted set of strings that contains "apple", "banana", and "orange". We then added "pear" to the set and displayed the set's contents using a foreach loop. Since the elements in the set are sorted, the output is in alphabetical order.
The C# SortedSet class provides an efficient way to maintain a collection of sorted, unique elements. It provides a range of operations to manipulate the set and is a valuable addition to the .NET framework's collection classes.