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?
To access the elements of the Jagged array user has to specify the row and column with the array name. It is possible to mix jagged and multidimensional arrays.
Below are the declaration and initialization of a 1-D jagged array that contains four two-dimensional array elements of different sizes. A user can access the individual elements as shown in the below example, which displays the value of the element [2, 0] of the second array (i.e value is 8)
In the initial example shown, we're just doing a map over that collection to pull out the specific values from the collection and put them into an array, which is then converted to a Set and back to an array. That conversion is what gives us our unique values.
The Array.filter function takes a callback whose first parameter is the current element in the operation. It also takes an optional index parameter and the array itself. Recommended:- JavaScript Array Reduce | Reduce Array to Single Value In this example, you will learn how to get unique values from array using iteration.
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();
A query expression method is
var query = (from arr in array
from value in arr
select value).Distinct();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With