tags:

views:

1032

answers:

3

Hello everyone,

I am using C# + VSTS2008 + .Net 3.0. I have an input as a string array. And I need to output the unique strings of the array. Any ideas how to implement this efficiently?

For example, I have input {"abc", "abcd", "abcd"}, the output I want to be is {"abc", "abcd"}.

thanks in avdance, George

+9  A: 

Using LINQ:

var uniquevalues = list.Distinct();

That gives you an IEnumerable<string>.

If you want an array:

string[] uniquevalues = list.Distinct().ToArray();


If you are not using .NET 3.5, it's a little more complicated:

List<string> newList = new List<string>();

foreach (string s in list)
{
   if (!newList.Contains(s))
      newList.Add(s);
}

// newList contains the unique values

Another solution (maybe a little faster):

Dictionary<string,bool> dic = new Dictionary<string,bool>();

foreach (string s in list)
{
   dic[s] = true;
}

List<string> newList = new List<string>(dic.Keys);

// newList contains the unique values
Philippe Leybaert
Sorry, I am wrong. I am using .Net 3.0, can not use LINQ, any solutions?
George2
Thanks Philippe, I like your reply!
George2
+4  A: 

Another option is to use a HashSet:

HashSet<string> hash = new HashSet<string>(inputStrings);

I think I'd also go with linq, but it's also an option.

Edit:
You've update the question to 3.0, maybe this will help: Using HashSet in C# 2.0, compatible with 3.5

Kobi
Thanks Kobi, I like your reply as well!
George2
No problem. It was obvious you'll take Philippe's answer (it's better), but it's always good to have more options.
Kobi
+1  A: 

You can go with Linq its short and sweet but in case u don't wanna LINQ try second Option HashSet

Option 1:

string []x = new string[]{"abc", "abcd", "abcd"};    
IEnumerable<string> y = x.Distinct();    
x = Enumerable.ToArray(y);

Option 2:

HashSet<string> ss = new HashSet<string>(x);
x = Enumerable.ToArray(ss);
Tumbleweed