Get N max numbers and their corresponding position(index) from a 2D array double[,] using lambda expression

穿精又带淫゛_ 提交于 2020-01-14 04:04:08

问题


This is a question similar to [ Get N max numbers from a List<int> using lambda expression ]

But I want to learn if I want to keep the index of those N max numbers, how should I write it using lambda expression.

Example) List<int> numbers = new List<int> { 12, 5, -8, 4, 7, 28, 3, 22 };

How can we get 4 maximum numbers by lambda: {28, 22, 12, 7} plus indexes { 5, 7, 0, 4}

as kirill suggested: var result = numbers.OrderByDescending(n => n).Take(4); but how can I get the index of those N max numbers? and it is a double[,] 2D array ( Not a list )


回答1:


Just to note: OrderBy + Take is an O(N*Log(N)) operation where "Top N" can be done much faster. https://codereview.stackexchange.com/questions/9773/optimizing-liststring-performance-in-c/9777#9777

Said that;

List<int> numbers = new List<int>() { 12, 5, -8, 4, 7, 28, 3, 22 };
var list = numbers.Select((n, i) => new { Num=n, Inx=i })
                    .OrderByDescending(x => x.Num)
                    .Take(4)
                    .ToList();


来源:https://stackoverflow.com/questions/13203766/get-n-max-numbers-and-their-corresponding-positionindex-from-a-2d-array-double

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