0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Is it possible to this with Hashset<>?
@Ryan yes and that was my first thought. But it might be overkill if all that is needed is a check for duplicates.
@ bytefire yes you are right first approach is better than hashset<> for this scenario.

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.