问题
One solution to extract unique values would be to apply Array[i].Distinct()
to each row and then form the list of all the unique elements from each row. Then we can repeat for this list List.Distinct()
.
But is there more efficient way how to create T[] UniqueValues
out of T[][] Data
? Thanks
回答1:
var distinct = array.SelectMany(a => a).Distinct().ToArray();
This simply flattens the nested arrays into a sequence and calls Distinct
to find the distinct elements. The call to ToArray
may be somewhat inefficient since the length of the distinct sequence is not known in advance. This is unlikely to be a problem if there are only a small number of distinct elements.
If you have a large input array, it may be quicker to copy the elements copy the elements into a new array, perform a radix sort and then iterate over the sorted array while skipping equal elements.
来源:https://stackoverflow.com/questions/15818046/efficiently-find-unique-elements-in-2-dim-array-t-in-c-sharp