codecompleting
codecompleting

Reputation: 9611

Is there an data type that acts both as a list and a dictionary?

Normally when I need to have a list of ints/strings/etc. I create a list like:

var list = new List<string>

And then I create a hashtable that contains all the strings, and I don't insert into the list unless it isn't in the hashtable i.e. to enforce unique items in the list.

Is there a datatype that can satisfy both of these requirements for me?

Upvotes: 0

Views: 177

Answers (7)

Cubicle.Jockey
Cubicle.Jockey

Reputation: 3328

HashSet<string> set = new HashSet<string>();

bool inserted = set.Add("Item");
bool insertedDuplicate = set.Add("Item");

inserted.Dump("Result1");
insertedDuplicate.Dump("Result2");

//Result
//Result1 = true
//Result2 = false

You can run this in LinqPad to see the functionality and how it works.

Upvotes: 0

Sergey Sirotkin
Sergey Sirotkin

Reputation: 1677

There is. Use HashSet:

var set = new HashSet<int>();
set.Add(4);
set.Add(4);   // there is already such an element in the set, no new elements added

Keep in mind, though, that it does not guarantee you the order of elements.

Upvotes: 6

user166390
user166390

Reputation:

Technically, there is System.Collections.Specialized.OrderedDictionary. However, this is an old non-updated (non-generic) class and I would generally recommend avoiding it ;-)

Represents a collection of key/value pairs that are accessible by the key or index.

In practice I would create a minimal wrapper class that exposes the required operations. (I would likely use a HashSet<T> (for existence) and a List<T> (for ordering), although just a single List<T> is far than sufficient for a relatively small n in most cases -- remember Big-O is about limits.)

Happy coding.

Upvotes: 0

Reddog
Reddog

Reputation: 15579

If you are after a set of unique values only (and don't subsequently care about ordering) then you should look at a HashSet<T>

Upvotes: 0

zellio
zellio

Reputation: 32494

You can use the HashSet<T> data type MSDN. Which will only allow you to have a single copy of each value.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062955

Do you just mean HashSet<string> ?

All elements in a HashSet<T> are unique; the Add() method returns a bool to indicate if a new item was actually added, or whether it was a no-op.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

Is there a datatype that can satisfy both of these requirements for me?

No. A hashtable will provide you a direct access to an element given its unique key, whereas in a list you don't need a key and you could definitely have duplicates.

Upvotes: 0

Related Questions