10

C# Array, How to make data in an array distinct from each other? For example

string[] a = {"a","b","a","c","b","b","c","a"}; 

how to get

string[]b = {"a","b","c"}
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
Prince OfThief
  • 6,323
  • 14
  • 40
  • 53

5 Answers5

20

Easiest way is the LINQ Distinct() command :

var b = a.Distinct().ToArray();
Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
Aidan
  • 4,783
  • 5
  • 34
  • 58
6

You might want to consider using a Set instead of an array. Sets can't contain duplicates so adding the second "a" would have no effect. That way your collection of characters will always contain no duplicates and you won't have to do any post processing on it.

Community
  • 1
  • 1
brain
  • 5,496
  • 1
  • 26
  • 29
2
var list = new HashSet<string> { };
list.Add("a");
list.Add("a");

var countItems = list.Count(); //in this case countItems=1
Dominique
  • 16,450
  • 15
  • 56
  • 112
Stefan P.
  • 9,489
  • 6
  • 29
  • 43
1

An array, which you start with, is IEnumerable<T>. IEnumerable<T> has a Distinct() method which can be used to manipulate the list into its distinct values

var distinctList = list.Distinct();

Finally,IEnumerable<T> has a ToArray() method:

var b = distinctList.ToArray();
Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

I think using c# Dictionary is the better way and I can sort by value using LINQ

Community
  • 1
  • 1
Prince OfThief
  • 6,323
  • 14
  • 40
  • 53