How to find unique values in jagged array

Posted by David Liddle on Stack Overflow See other posts from Stack Overflow or by David Liddle
Published on 2010-04-04T23:15:58Z Indexed on 2010/04/04 23:23 UTC
Read the original article Hit count: 337

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ