views:

1225

answers:

6

I want to store some values in a balanced binary search tree using C#. I looked through the collections in the generics namespace and I haven't found an equivalent of the stl set.

What generic collection can I use? (I don't want to store key/value pairs... just values.)

+7  A: 

You could use an HashSet

The HashSet<T> class provides high performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

The capacity of a HashSet<T> object is the number of elements that the object can hold. A HashSet<T> object's capacity automatically increases as elements are added to the object.

Luca Martinetti
FWIW, this isn't exactly what you're looking for-- it doesn't use a binary tree, but a hash table. This makes the performance better, so is generally preferred, AFAIK.
Devin Jeanpierre
+2  A: 

HashSet, but HashSet isn't available in version 2.0 of the framework. If you need something for 2.0 then use Dictionary, and specify a dummy type (e.g. object, int, or bool) for which you supply a dummy value (e.g. null, 0, or false) as the second/value parameter (i.e. use the Dictionary as a set of keys without caring about the associated values).

ChrisW
+3  A: 

Try RedBlackTree.NET. It's in VB but I think it can be easily converted to C#.

And I believe some of the collection type actually uses a red-black tree internally. So you might want to decompile the framework itself and look around for some clues.

I don't think a binary tree can be replaced by a HashSet. Their performance characteristics are different, roughly:

HashSet - O(1) lookup (n) search
Binary search tree - O(log n) lookup O(log n) search

If you want to store the values and later perform a search, you will want to be using a binary tree instead of a HashSet.

chakrit
That's true: an STL set is sorted whereas a C# HashSet isn't.
ChrisW
+2  A: 

The C5 Collection Library probably has what you want.

Joel Mueller
Agreed. C5 is a far more well designed library than the collections included with .NET.
Matt Olenik
+3  A: 
  1. If you require sorted set, use SortedDictionary<T,U>. This is implemented using a binary search tree. Admittedly, you will be using 64-bits per entry because you are storing a key-value pair underneath. You can write a wrapper around it like this:

    class Set<T> : SortedDictionary<T, bool>
    {
        public void Add(T item)
        {
            this.Add(item, true);
        }
    }
    
  2. If you don't require a sorted set, use HashSet<T>.

  3. Otherwise, check out C5 Generic Collection Library. In particular TreeSet<T>. It is a red-black tree and only stores the values.

siz
+1  A: 

Try with IESI Collections.

They're used by NHibernate, so should be good implementations.

emirc