How to get unique values from a collection in C#?
Solution 1
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
Solution 2
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
Solution 3
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);
George2
Updated on June 06, 2022Comments
-
George2 almost 2 years
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"}.
-
Kobi over 14 yearsNo problem. It was obvious you'll take Philippe's answer (it's better), but it's always good to have more options.