Reputation: 45771
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"}.
Upvotes: 3
Views: 11205
Reputation: 14335
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);
Upvotes: 2
Reputation: 171744
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
Upvotes: 19
Reputation: 138007
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
Upvotes: 9