views:

744

answers:

3

What is the most efficient way to store a list of strings ignoring any duplicates? I was thinking a dictionary may be best inserting strings by writing dict[str] = false; and enumerating through the keys as a list. Is that a good solution?

+14  A: 

If you are using .NET 3.5, the HashSet should work for you.

The HashSet<(Of <(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.

JP Alioto
+1  A: 

This is not part of the the system namespace but have used the Iesi.Collections from http://www.codeproject.com/KB/recipes/sets.aspx with NHibernate. It has support for hashed set along with sorted set, dictionary set, and so on. Since it has been used with NHibernate it has been used extensively and very stable. This also does not require .Net 3.5

AndrewB
A: 

You can look to do something like this

 var hash = new HashSet<string>();
    var collectionWithDup = new []{"one","one","two","one","two","zero"}; 

    foreach (var str in collectionWithDup)
        if(!hash.Contains(str))
            hash.Add(str);
Perpetualcoder
You don't need the Contains check with a HashSet. You can just call the Add method directly and it will return true or false depending on whether or not the item already exists.
LukeH