C# | Remove elements from a SortedSet that match the predicate
Last Updated :
01 Feb, 2019
SortedSet class represents the collection of objects in sorted order. This class comes under the System.Collections.Generic namespace. SortedSet<T>.RemoveWhere(Predicate<T>) Method is used to remove all elements that match the conditions defined by the specified predicate from a SortedSet<T>.
Properties:
- In C#, SortedSet class can be used to store, remove or view elements.
- It maintains ascending order and does not store duplicate elements.
- It is suggested to use SortedSet class if you have to store unique elements and maintain ascending order.
Syntax:
public int RemoveWhere (Predicate<T> match);
Return Value: This method returns the number of elements that were removed from the SortedSet<T> collection.
Exception: This method will give ArgumentNullException if the match is null.
Note: Calling this method is an O(n) operation, where n is Count i.e, the number of elements that are contained in the SortedSet.
Below are the examples to illustrate the SortedSet<T>.RemoveWhere(Predicate<T>) Method
Example 1:
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
SortedSet< int > mySet = new SortedSet< int >();
for ( int i = 0; i < 10; i++) {
mySet.Add(i);
}
Console.WriteLine( "The elements in SortedSet are : " );
foreach ( int i in mySet)
{
Console.WriteLine(i);
}
Console.WriteLine( "Number of elements are : " + mySet.Count);
mySet.RemoveWhere(isEven);
Console.WriteLine( "The elements in SortedSet are : " );
foreach ( int i in mySet)
{
Console.WriteLine(i);
}
Console.WriteLine( "Number of elements are : " + mySet.Count);
}
private static bool isEven( int i)
{
return ((i % 2) == 0);
}
}
|
Output:
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
Example 2 :
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
SortedSet< int > mySet = new SortedSet< int >();
for ( int i = 0; i < 20; i++) {
mySet.Add(i);
}
Console.WriteLine( "Number of elements are : " + mySet.Count);
mySet.RemoveWhere(myFunc);
Console.WriteLine( "Number of elements are : " + mySet.Count);
}
private static bool myFunc( int i)
{
return ((i % 2) == 0 && (i % 3 == 0));
}
}
|
Output:
Number of elements are : 20
Number of elements are : 16
Reference:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...