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"}

5 Answers 5

20

Easiest way is the LINQ Distinct() command :

var b = a.Distinct().ToArray();
Sign up to request clarification or add additional context in comments.

1 Comment

Distinct returns an IEnumerable<T>. You need the the ToArray() to cast it to an array.
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.

Comments

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

var countItems = list.Count(); //in this case countItems=1

Comments

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();

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.