iefpw
iefpw

Reputation: 7062

Distinct value using hashtable

I'm doing distinct values when like looping through a list of values or fields.

Dictionary<string, int> _ddistinctValues = new Dictionary<string, int>();

foreach(string _word in _words) {
 if(!_ddistinctValues.ContainsKey(_word)) {
    _ddistinctValues.Add(_word, 1);
 }
}

Is there a better ways to do this without saving the "1" integer value to save space? I'm using hashtable to get distinct values faster. Maybe hash the wordname without the value, just distinct keys? Is there a class in C# that can do this?

It is not a big issue. Just wondering.

Thanks.

Upvotes: 2

Views: 3753

Answers (3)

SLaks
SLaks

Reputation: 888047

You're looking for a HashSet<string>.

Upvotes: 1

Joachim Isaksson
Joachim Isaksson

Reputation: 181057

Yes, HashSet is the class for you.

Upvotes: 1

Jeff Mercado
Jeff Mercado

Reputation: 134571

Just use LINQ and call Distinct() on the list. You might want to throw the results into another list.

var distinctWords = _words.Distinct().ToList();

This would internally use a HashSet<T> to determine uniqueness which would be the collection you'd be interested in.

Upvotes: 5

Related Questions