SortedSet类按排序顺序表示对象的集合。此类位于System.Collections.Generic命名空间下。 SortedSet
特性:
- 在C#中,SortedSet类可用于存储,删除或查看元素。
- 它保持升序,并且不存储重复的元素。
- 如果必须存储唯一元素并保持升序,建议使用SortedSet类。
句法:
public int RemoveWhere (Predicate match);
返回值:该方法返回从SortedSet
异常:如果匹配为null,则此方法将提供ArgumentNullException。
注意:调用此方法是一个O(n)操作,其中n是Count,即SortedSet中包含的元素数。
以下示例说明了SortedSet
范例1:
// C# code to remove elements from a SortedSet
// that match the predicate
using System;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a SortedSet of integers
SortedSet mySet = new SortedSet();
// Inserting elements into SortedSet
for (int i = 0; i < 10; i++) {
mySet.Add(i);
}
Console.WriteLine("The elements in SortedSet are : ");
// Displaying the elements in SortedSet
foreach(int i in mySet)
{
Console.WriteLine(i);
}
// Displaying the number of elements in SortedSet
Console.WriteLine("Number of elements are : " + mySet.Count);
// Remove elements from a SortedSet
// with conditions defined by the predicate
mySet.RemoveWhere(isEven);
Console.WriteLine("The elements in SortedSet are : ");
// Displaying the elements in SortedSet
foreach(int i in mySet)
{
Console.WriteLine(i);
}
// Displaying the number of elements in SortedSet
Console.WriteLine("Number of elements are : " + mySet.Count);
}
// Helper function which tells
// whether an element is even or not
private static bool isEven(int i)
{
return ((i % 2) == 0);
}
}
输出:
The elements in SortedSet are :
0
1
2
3
4
5
6
7
8
9
Number of elements are : 10
The elements in SortedSet are :
1
3
5
7
9
Number of elements are : 5
范例2:
// C# code to remove elements from a
// SortedSet that match the predicate
using System;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a SortedSet of integers
SortedSet mySet = new SortedSet();
// Inserting elements into SortedSet
for (int i = 0; i < 20; i++) {
mySet.Add(i);
}
// Displaying the number of elements in SortedSet
Console.WriteLine("Number of elements are : " + mySet.Count);
// Remove elements from a SortedSet
// with conditions defined by the predicate
mySet.RemoveWhere(myFunc);
// Displaying the number of elements in SortedSet
Console.WriteLine("Number of elements are : " + mySet.Count);
}
// Helper function which tells
// whether an element is divisible
// by both 2 and 3
private static bool myFunc(int i)
{
return ((i % 2) == 0 && (i % 3 == 0));
}
}
输出:
Number of elements are : 20
Number of elements are : 16
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.sortedset-1.removewhere?view=netframework-4.7.2