5

I would like to know how I can count the number of unique values in a jagged array.

My domain object contains a string property that has space delimitered values.

class MyObject
{
    string MyProperty; //e.g = "v1 v2 v3"
}

Given a list of MyObject's how can I determine the number of unique values?

The following linq code returns an array of jagged array values. A solution would be to store a temporary single array of items, looped through each jagged array and if values do not exist, to add them. Then a simple count would return the unique number of values. However, was wondering if there was a nicer solution.

db.MyObjects.Where(t => !String.IsNullOrEmpty(t.MyProperty))
    .Select(t => t.Categories.Split(new char[] { ' ' },
        StringSplitOptions.RemoveEmptyEntries))
    .ToArray()

Below is a more readable example:

array[0] = { "v1", "v2", "v3" }
array[1] = { "v1" }
array[2] = { "v4", "v2" }
array[3] = { "v1", "v5" }

From all values the unique items are v1, v2, v3, v4, v5.

The total number of unique items is 5.

Is there a solution, possibly using linq, that returns either only the unique values or returns the number of unique values?

2 Answers 2

8

Yes, with LINQ this is quite simple. First use SelectMany to flatten the jagged array into an IEnumerable<string> containing all values and then call Distinct to select only unique values:

IEnumerable<string> uniqueValues = array.SelectMany(x => x).Distinct();

If you want to count them then use Count:

IEnumerable<string> uniqueValues = array.SelectMany(x => x).Distinct();
int uniqueCount = uniqueValues.Count();
Sign up to request clarification or add additional context in comments.

Comments

5

A query expression method is

var query = (from arr in array
             from value in arr
             select value).Distinct();

1 Comment

Just an FYI for readers...this answer and Mark Byers answer are effectively the same thing with different syntax. The fundamental answer is "Select Many". :)

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.