NavigableSet<T> Class
Definition
Represents a sorted set augmented with order statistics - an ISet<T> that keeps its elements in comparer order and answers nearest-neighbour (TryGetFloor(T, out T) / TryGetCeiling(T, out T) / TryGetHigher(T, out T) / TryGetLower(T, out T)), rank/select (IndexOf(T) / GetAt(int)), and range-counting queries in O(log n).
public sealed class NavigableSet<T> : ISet<T>, ICollection<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable where T : notnull
Type Parameters
TThe type of elements in the set. Elements must not be null.
- Inheritance
-
NavigableSet<T>
- Implements
-
ISet<T>ICollection<T>IEnumerable<T>
- Inherited Members
- Extension Methods
Examples
var prices = new NavigableSet<decimal>();
prices.Add(10.00m);
prices.Add(10.25m);
prices.Add(10.50m);
prices.TryGetFloor(10.30m, out decimal floor); // 10.25 - greatest element <= 10.30
prices.TryGetCeiling(10.30m, out decimal ceiling);// 10.50 - least element >= 10.30
int rank = prices.IndexOf(10.25m); // 1 - zero-based rank in sorted order
decimal median = prices.GetAt(prices.Count / 2); // 10.25 - k-th smallest
int inBand = prices.CountInRange(10.00m, 10.30m); // 2 - O(log n), no iteration
Remarks
NavigableSet<T> is backed by an order-statistic red-black tree: every node carries the size of its
subtree, maintained through all rotations, so positional queries read only size fields on a root-to-node path. See
Bodu.Collections/docs/navigable-collections-design.md for the backing-structure decision record.
Compared with SortedSet<T>, this type adds rank/select (IndexOf(T) is the zero-based rank of an element; GetAt(int) is the k-th smallest element), O(log n) CountInRange(T, T), the four nearest-neighbour queries, and cheap Ascending() / Descending() / Range(T, T) views. Unlike SortedSet<T>, null elements are rejected, consistent with the rest of the Bodu collection family.
Elements that the comparer orders equal are treated as duplicates: Add(T) returns false and preserves the stored element.
This type is not thread-safe.
Constructors
NavigableSet()
Initializes a new instance of the NavigableSet<T> class using the default comparer.
public NavigableSet()
NavigableSet(IComparer<T>?)
Initializes a new instance of the NavigableSet<T> class using the specified comparer.
public NavigableSet(IComparer<T>? comparer)
Parameters
NavigableSet(IEnumerable<T>, IComparer<T>?)
Initializes a new instance of the NavigableSet<T> class containing the distinct elements from
source, bulk-loaded into a balanced tree.
public NavigableSet(IEnumerable<T> source, IComparer<T>? comparer = null)
Parameters
sourceIEnumerable<T>The source collection. Must not be null.
comparerIComparer<T>The ordering comparer, or null to use the default comparer.
Remarks
The source is sorted and deduplicated (comparer-equal duplicates keep the first occurrence), then built directly into a balanced tree - O(n log n) overall, O(n) after the sort.
Exceptions
- ArgumentNullException
sourceis null.- ArgumentException
sourcecontains a null element.
Properties
Comparer
Gets the comparer that defines the element ordering.
public IComparer<T> Comparer { get; }
Property Value
- IComparer<T>
The active ordering comparer.
Count
Gets the number of elements in the set.
public int Count { get; }
Property Value
- int
The number of elements currently stored in the set.
IsReadOnly
Gets a value indicating whether the set is read-only.
public bool IsReadOnly { get; }
Property Value
Max
Gets the largest element in the set.
public T Max { get; }
Property Value
- T
The maximum element under the active comparer.
Exceptions
- InvalidOperationException
The set is empty.
Min
Gets the smallest element in the set.
public T Min { get; }
Property Value
- T
The minimum element under the active comparer.
Exceptions
- InvalidOperationException
The set is empty.
Methods
Add(T)
Adds the specified item to the set.
public bool Add(T item)
Parameters
itemTThe item to add. Must not be null.
Returns
- bool
true if the item was added; otherwise, false when the set already contains a comparer-equal element.
Exceptions
- ArgumentNullException
itemis null.
Ascending()
Returns a live view of the set in ascending comparer order.
public IEnumerable<T> Ascending()
Returns
- IEnumerable<T>
A lazily evaluated sequence over the current elements, smallest first.
Remarks
The view is live: each fresh iteration re-resolves against the set's current state, so mutations made after the view was obtained are reflected the next time it is iterated. Within a single iteration the view is fail-fast - any structural mutation causes the next advance to throw InvalidOperationException.
Clear()
Removes all elements from the set.
public void Clear()
Contains(T)
Determines whether the set contains the specified item.
public bool Contains(T item)
Parameters
itemTThe item to locate. Must not be null.
Returns
Exceptions
- ArgumentNullException
itemis null.
CopyTo(T[], int)
Copies the elements to the specified array in ascending order, starting at arrayIndex.
public void CopyTo(T[] array, int arrayIndex)
Parameters
Exceptions
- ArgumentNullException
arrayis null.- ArgumentOutOfRangeException
arrayIndexis negative.- ArgumentException
arraydoes not have enough space starting atarrayIndex.
CountInRange(T, T)
Returns the number of elements within the inclusive range [lowInclusive,
highInclusive].
public int CountInRange(T lowInclusive, T highInclusive)
Parameters
lowInclusiveTThe inclusive lower bound. Must not be null.
highInclusiveTThe inclusive upper bound. Must not be null.
Returns
- int
The count of stored elements no smaller than the lower bound and no larger than the upper bound.
Remarks
Runs in O(log n) as a subtraction of two rank walks; neither bound needs to be present in the set.
Exceptions
- ArgumentNullException
lowInclusiveorhighInclusiveis null.- ArgumentException
lowInclusiveorders afterhighInclusiveunder the active comparer.
Descending()
Returns a live view of the set in descending comparer order.
public IEnumerable<T> Descending()
Returns
- IEnumerable<T>
A lazily evaluated sequence over the current elements, largest first.
Remarks
The view is live: each fresh iteration re-resolves against the set's current state, so mutations made after the view was obtained are reflected the next time it is iterated. Within a single iteration the view is fail-fast - any structural mutation causes the next advance to throw InvalidOperationException.
ExceptWith(IEnumerable<T>)
Modifies the current set so that it contains only elements that are not present in other.
public void ExceptWith(IEnumerable<T> other)
Parameters
otherIEnumerable<T>The collection to subtract. Must not be null.
Remarks
Removes element-at-a-time - O(m log n) for m elements in other.
Exceptions
- ArgumentNullException
otheris null.
GetAt(int)
Returns the element at the specified zero-based rank - the k-th smallest element.
public T GetAt(int rank)
Parameters
rankintThe zero-based rank of the element to select.
Returns
- T
The element whose rank is
rank.
Remarks
Runs in O(log n) by descending on subtree sizes.
Exceptions
- ArgumentOutOfRangeException
rankis negative or greater than or equal to Count.
GetEnumerator()
Returns an enumerator that iterates through the set in ascending comparer order.
public NavigableSet<T>.Enumerator GetEnumerator()
Returns
- NavigableSet<T>.Enumerator
An NavigableSet<T>.Enumerator over the set elements.
IndexOf(T)
Returns the zero-based rank of value in ascending comparer order.
public int IndexOf(T value)
Parameters
valueTThe element to locate. Must not be null.
Returns
- int
The number of elements smaller than
value, or-1if it is not present.
Remarks
Runs in O(log n) by accumulating subtree sizes along the search path.
Exceptions
- ArgumentNullException
valueis null.
IntersectWith(IEnumerable<T>)
Modifies the current set so that it contains only elements that are also present in other.
public void IntersectWith(IEnumerable<T> other)
Parameters
otherIEnumerable<T>The collection to intersect with. Must not be null.
Remarks
Sorts other into a scratch array under this set's comparer and merge-walks it against the
in-order enumeration to find the non-members - O(n + m log m) overall, with no tree nodes allocated for
other.
Exceptions
- ArgumentNullException
otheris null.
IsProperSubsetOf(IEnumerable<T>)
Determines whether the current set is a proper (strict) subset of other.
public bool IsProperSubsetOf(IEnumerable<T> other)
Parameters
otherIEnumerable<T>The collection to test against. Must not be null.
Returns
Exceptions
- ArgumentNullException
otheris null.
IsProperSupersetOf(IEnumerable<T>)
Determines whether the current set is a proper (strict) superset of other.
public bool IsProperSupersetOf(IEnumerable<T> other)
Parameters
otherIEnumerable<T>The collection to test against. Must not be null.
Returns
Exceptions
- ArgumentNullException
otheris null.
IsSubsetOf(IEnumerable<T>)
Determines whether the current set is a subset of other.
public bool IsSubsetOf(IEnumerable<T> other)
Parameters
otherIEnumerable<T>The collection to test against. Must not be null.
Returns
Exceptions
- ArgumentNullException
otheris null.
IsSupersetOf(IEnumerable<T>)
Determines whether the current set is a superset of other.
public bool IsSupersetOf(IEnumerable<T> other)
Parameters
otherIEnumerable<T>The collection to test against. Must not be null.
Returns
Exceptions
- ArgumentNullException
otheris null.
Overlaps(IEnumerable<T>)
Determines whether the current set and other share any elements.
public bool Overlaps(IEnumerable<T> other)
Parameters
otherIEnumerable<T>The collection to test against. Must not be null.
Returns
Exceptions
- ArgumentNullException
otheris null.
Range(T, T)
Returns a live view of the elements within the inclusive range [lowInclusive,
highInclusive] in ascending comparer order.
public IEnumerable<T> Range(T lowInclusive, T highInclusive)
Parameters
lowInclusiveTThe inclusive lower bound. Must not be null.
highInclusiveTThe inclusive upper bound. Must not be null.
Returns
- IEnumerable<T>
A lazily evaluated sequence over the in-range elements, smallest first.
Remarks
The bounds need not be present in the set. The walk descends directly to the first in-range element and stops past the last, so iterating costs O(log n + k) for k yielded elements.
The view is live over the bound pair: each fresh iteration re-resolves against the set's current state. Within a single iteration the view is fail-fast - any structural mutation causes the next advance to throw InvalidOperationException.
Exceptions
- ArgumentNullException
lowInclusiveorhighInclusiveis null.- ArgumentException
lowInclusiveorders afterhighInclusiveunder the active comparer.
Remove(T)
Removes the specified item from the set.
public bool Remove(T item)
Parameters
itemTThe item to remove. Must not be null.
Returns
Exceptions
- ArgumentNullException
itemis null.
SetEquals(IEnumerable<T>)
Determines whether the current set contains exactly the same elements as other.
public bool SetEquals(IEnumerable<T> other)
Parameters
otherIEnumerable<T>The collection to compare against. Must not be null.
Returns
- bool
true if the two collections contain the same elements (ignoring duplicates and order); otherwise, false.
Exceptions
- ArgumentNullException
otheris null.
SymmetricExceptWith(IEnumerable<T>)
Modifies the current set so that it contains only elements that are present either in the current set or in
other, but not in both.
public void SymmetricExceptWith(IEnumerable<T> other)
Parameters
otherIEnumerable<T>The collection to apply symmetric difference with. Must not be null.
Remarks
Sorts and deduplicates other into a scratch array and toggles membership per distinct
element - O(m log m + m log n) overall, with no tree nodes allocated for other.
Exceptions
- ArgumentNullException
otheris null.
TryGetCeiling(T, out T)
Attempts to get the least element greater than or equal to value.
public bool TryGetCeiling(T value, out T ceiling)
Parameters
valueTThe reference value. Must not be null.
ceilingTWhen this method returns true, the ceiling element.
Returns
Exceptions
- ArgumentNullException
valueis null.
TryGetFloor(T, out T)
Attempts to get the greatest element less than or equal to value.
public bool TryGetFloor(T value, out T floor)
Parameters
valueTThe reference value. Must not be null.
floorTWhen this method returns true, the floor element.
Returns
Exceptions
- ArgumentNullException
valueis null.
TryGetHigher(T, out T)
Attempts to get the least element strictly greater than value.
public bool TryGetHigher(T value, out T higher)
Parameters
valueTThe reference value. Must not be null.
higherTWhen this method returns true, the next-higher element.
Returns
Exceptions
- ArgumentNullException
valueis null.
TryGetLower(T, out T)
Attempts to get the greatest element strictly less than value.
public bool TryGetLower(T value, out T lower)
Parameters
valueTThe reference value. Must not be null.
lowerTWhen this method returns true, the next-lower element.
Returns
Exceptions
- ArgumentNullException
valueis null.
TryGetMax(out T)
Attempts to get the largest element in the set.
public bool TryGetMax(out T max)
Parameters
maxTWhen this method returns true, the maximum element.
Returns
TryGetMin(out T)
Attempts to get the smallest element in the set.
public bool TryGetMin(out T min)
Parameters
minTWhen this method returns true, the minimum element.
Returns
UnionWith(IEnumerable<T>)
Modifies the current set so that it contains every element that is present in either this set or
other.
public void UnionWith(IEnumerable<T> other)
Parameters
otherIEnumerable<T>The collection to union with. Must not be null.
Remarks
Adds element-at-a-time - O(m log(n + m)) for m elements in other.
Exceptions
- ArgumentNullException
otheris null.
Explicit Interface Implementations
ICollection<T>.Add(T)
Adds item via the Add(T) contract.
void ICollection<T>.Add(T item)
Parameters
itemTThe item to add.
Remarks
IEnumerable<T>.GetEnumerator()
Returns an enumerator that iterates through the collection.
IEnumerator<T> IEnumerable<T>.GetEnumerator()
Returns
- IEnumerator<T>
An enumerator that can be used to iterate through the collection.
IEnumerable.GetEnumerator()
Returns an enumerator that iterates through a collection.
IEnumerator IEnumerable.GetEnumerator()
Returns
- IEnumerator
An IEnumerator object that can be used to iterate through the collection.
Applies to
| Product | Versions |
|---|---|
| .NET | 8, 10 |