tags:

views:

150

answers:

4

I need a HashSet that preserves insertion ordering, are there any implementations of this in the framework?

+4  A: 

That defeats the purpose of a HashSet. For sequences that need to persist order, look at List<T> or LinkedList<T> etc.

Rex M
What happens if you need an ordered set? ie. the semantics of uniqueness of entries, but still needed ordering?
Matthew Scharley
Wrap a collection around IList and IDictionary adding to both.
csharptest.net
@Matthew I don't think the Framework provides a Set class in the sense you're describing. Somewhat unfortunate, but also not especially difficult to implement.
Rex M
A: 

Rex is correct -- the entire purpose of a hash is to facilitate quick access to the data, which destroys ordering.

What, exactly, are you trying to do? List and linked lists preserve ordering, as Rex indicated. Sparse arrays might be an alternative? Maps and linked lists aren't going to do what you say you want.

jfawcett
A: 

OrderedSet in Wintellect's Power Collections provides an implementation.

If you want a workaround that only uses framework stuff you can always defer making the list distinct till the end of the process and use the LINQ Distinct call at the end which preserves ordering.

Sam Saffron
+1  A: 

In the case that the CLR lacks what you're describing (which it seems to), I wrote a Set class a while back as an intellectual excercise that seems to have the semantics you describe. No guarantees beyond that it works though.

void Main()
{
    Set<int> foo = new Set<int>();
    foo.Add(5);
    foo.Add(10);
    foo.Add(5);
    foo.Add(2);

    // Prints 5, 10, 2
    foreach(int i in foo)
    {
     i.Dump();
    }
}
Matthew Scharley