2009-07-23 59 views
11

我有以下的整數數組:如何使用LINQ獲取int數組中的前3個元素?

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); 

當我檢查有什麼topThree裏面,我發現:

{System.Linq.Enumerable.TakeIterator}
計數:0

我做錯了什麼,如何糾正我的代碼?

+4

topThree中的對象不是*結果*,它是*查詢*。 top3是一個對象,意思是「將數組中的項目順序從最高排序到最低並取前三位」。這是*全部*它的意思。這並不意味着「8,6,5」。它意味着*查詢*,而不是*結果*。您可以通過執行查詢,然後更改數組,然後再次執行查詢來演示此操作。查詢完全相同,但結果不同。 – 2009-07-23 15:59:46

回答

23

你是怎麼「檢查top3裏面的東西」的?這樣做最簡單的方法是將它們打印出來:

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); 
+0

我在QuickWatch中檢查過它。感謝您讓事情更清楚。 – 2009-07-23 05:33:29

+2

QuickWatch可能是保守的,除非你確實要求,否則不要爲你執行代碼。查詢實際上沒有數據 - 它只知道如何獲取數據。獲取數據可能很慢,或者可能有副作用,所以在默認情況下將數據顯示在調試器中是一個壞主意。 – 2009-07-23 06:03:29

+0

「有可能更有效的方法來找到排序的前N個值」 - 您能提供一個更有效的方法的例子嗎? – 2017-09-14 03:39:28

11

你的代碼看起來沒什麼問題,你也許想要得到的結果返回給另一個數組?

int[] topThree = array.OrderByDescending(i=> i) 
         .Take(3) 
         .ToArray(); 
3

由於延遲執行linq查詢。

如果您添加.ToArray()或.ToList()或類似的建議,您將得到正確的結果。

-1
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); 
相關問題