Geeky Ninja
Geeky Ninja

Reputation: 6052

How to identify multiple occurrence of a record in string array

I have one string[] and its has only 4 possible values like "www", "xxx", "yyy" and "zzz".

In a request to my application different combinations of values came in this string[], like:

Case 1: Single value multiple time:

string[] a = {"xxx", "xxx", "xxx"}; //only "xxx" is present in array multiple times

Case 2: Multiple values single time:

string[] a = {"xxx", "zzz", "yyy"}; //only single value is present for "xxx", "zzz" and "yyy"

Case 3: Multiple values multiple times:

string[] a = {"xxx", "zzz", "xxx", "yyy", "zzz"}; //"xxx" and "zzz" are present multiple times

Now, what could be the best possible way to find out that only a single value in coming multiple time or multiple values are coming either single or multiple time?

Upvotes: 0

Views: 72

Answers (1)

bytefire
bytefire

Reputation: 4412

You can use something like this:

int count = a.Distinct().Count();

And then compare count with total values in the array, i.e. a.Length. If they are same then every value is repeated once.

count contains the number of time a unique value appears in the array.

Using HashSet

int count = new HashSet<string>(a).Count;

However the first approach is recommended.

Upvotes: 2

Related Questions