Efficiently find unique elements in 2-dim array T[][] in C#

安稳与你 提交于 2019-12-11 03:24:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!