tags:

views:

751

answers:

4

What would you recommend for class that needs to keep a list of unique integers?

I'm going to want to Add() integers to the collection and also check for existence e.g. Contains().

Would be nice to also get them in a list as a string for display, ie. "1, 5, 10, 21".

+16  A: 

HashSet

Tom Ritter
I looked at the arraylist and it is certainly better than arraylist, so I removed my previous answer.
EBGreen
HashSet is going to ToString the type ... not a list. And the list that he is displaying is one of order, that HashSet doesn't support.
MagicKat
Correct. To get the string list, you would use code like: int[] a = h.ToArray<int>(); Array.Sort<int>(a); string.Join(', ', a);This is not high performance, but I get the impression it's not a common operation, and is more for debugging/viewing than computation.
Tom Ritter
+1  A: 

If you can't use .NET 3.5, then you can't use HashSet. If that's the case, it's easy to roll your own based on the Dictionary structure.

public class Set<T> {
    private class Unit { ... no behavior }
    private Dictionary<T, Unit> d;

....
}

Unit is intended to be a type with exactly one value. It doesn't matter what you map elements to, just use the keys to know what's in your set. The operations you asked for in the question are straightforward to implement.

Denis Bueno
Why even create `Unit` classes? The value can be `null`.
Joel B Fant
What would the type be? "object"?
Denis Bueno
Yes, Dictionary<T, Object> would work fine for this.
Bob King
A: 

you could inherit a class from KeyedCollection. This way your key can be the value itself, you can override the ToString so that you get your desired output. This could give you the behaviour you want/need.

Note, this answer was for the framework 2.0 part of the Q

mattlant
+2  A: 

In my testing, I have found that a Dictionary with a dummy value is faster than a HashSet, when dealing with very large sets of data (100,000+ in my case). I expect this is because the Dictionary allows you to set an initial capacity, but I don't really know. In the case you're describing, I would probably use the Dictionary if I was expecting a very large set of numbers, and then (or as I was adding to the Dictionary, depending on the intent) iterate over it using a string builder, to create the output string.

Timothy Carter