Question

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"}
Was it helpful?

Solution

Easiest way is the LINQ Distinct() command :

var b = a.Distinct().ToArray();

OTHER TIPS

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.

    var list = new HashSet<string> { };
    list.Add("a");
    list.Add("a");

    var countItems = list.Count(); //in this case countItems=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();

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top