3

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"}.

jessehouwing
  • 106,458
  • 22
  • 256
  • 341
George2
  • 44,761
  • 110
  • 317
  • 455

3 Answers3

19

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
  • 168,566
  • 31
  • 210
  • 223
9

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

Community
  • 1
  • 1
Kobi
  • 135,331
  • 41
  • 252
  • 292
  • No problem. It was obvious you'll take Philippe's answer (it's better), but it's always good to have more options. – Kobi Jul 30 '09 at 11:38
2

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);
shahjapan
  • 13,637
  • 22
  • 74
  • 104