How to get unique values ​​from a collection in C #?

I am using C # + VSTS2008 + .Net 3.0. I have input as a string array. And I need to output unique array lines. Any ideas how to implement this effectively?

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

+3
source share
3 answers

Using LINQ:

var uniquevalues = list.Distinct();

It gives you IEnumerable<string>.

If you need an array:

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

If you are not using .NET 3.5, this is a little trickier:

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
+19
source

Another option is to use HashSet:

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

, linq, .

Edit:
3.0, , : HashSet # 2.0, 3.5

+9

You can go with Linq your short and sweet, but in case you do not want LINQ to try the 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);
+2
source

Source: https://habr.com/ru/post/1713939/


All Articles