How to find unique values in jagged array
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 uni开发者_如何学运维que values or returns the number of unique values?
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();
精彩评论