[英]How to get the top 3 elements in an int array using LINQ?
我有以下整數數組:
int[] array = new int[7] { 1, 3, 5, 2, 8, 6, 4 };
我編寫了以下代碼來獲取數組中的前3個元素:
var topThree = (from i in array orderby i descending select i).Take(3);
當我檢查topThree
,我發現:
{System.Linq.Enumerable.TakeIterator}
數:0
我做錯了什么,我該如何糾正我的代碼?
您如何“檢查topThree中的內容”? 最簡單的方法是將它們打印出來:
using System;
using System.Linq;
public class Test
{
static void Main()
{
int[] array = new int[7] { 1, 3, 5, 2, 8, 6, 4 };
var topThree = (from i in array
orderby i descending
select i).Take(3);
foreach (var x in topThree)
{
Console.WriteLine(x);
}
}
}
對我來說還好...
找到最高的N個值可能比排序更有效的方法,但這肯定會起作用。 您可能要考慮對僅使用一件事的查詢使用點表示法:
var topThree = array.OrderByDescending(i => i)
.Take(3);
您的代碼對我來說似乎很好,您可能想將結果返回到另一個數組?
int[] topThree = array.OrderByDescending(i=> i)
.Take(3)
.ToArray();
這是由於linq查詢的執行延遲。
如建議的那樣,如果添加.ToArray()或.ToList()或類似內容,您將獲得正確的結果。
int[] intArray = new int[7] { 1, 3, 5, 2, 8, 6, 4 };
int ind=0;
var listTop3 = intArray.OrderByDescending(a=>a).Select(itm => new {
count = ++ind, value = itm
}).Where(itm => itm.count < 4);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.