问题
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