2013-04-22 149 views
-1

我想使用linq to Entities將top記錄按降序列Value1排序。linq to EF,如何使用'top`方法

我知道我CA寫像:

MyCollection.OrderByDescending(項目=> item.Value1).FirstOrDefault();

但是,如何使用以下方法Top

System.Data.Objects.ObjectQuery.Top(字符串,則params System.Data.Objects.ObjectParameter [])

+0

http://msdn.microsoft.com/ru-ru/library/bb300906.aspx – 2kay 2013-04-22 08:14:49

回答

5

編輯:當問題是特別有關的LINQ to SQL這個答案寫。

System.Data.Objects用於實體框架,而不是LINQ到遠SQL我可以告訴 - 而是要找到SQL甚至LINQ的前N值或者LINQ到對象,你通常只使用Take

var query = db.Customers 
       .OrderByDescending(c => c.Value1) 
       .Take(10); 

(我真的鼓勵你嘗試雖然比Value1使用更有意義的名稱......)

編輯:即使是在實體框架,我通常是在LINQ查詢中使用Take - 這是代表性的「LINQ方式」前N個結果。如果您確實想要使用Top,則documentation會提供示例 - 但您應該考慮爲什麼要使用Top而不是Take。 (你給我們沒有上下文來處理。)

+0

我的不好,我的意思是實體。我知道這個語法。我特別詢問了「top」語法。我找到了答案:'Top(1,new ObjectParameter(「@ CtidProdId」))。Select(item => item.CtidProdId).SingleOrDefault()' – 2013-04-22 08:18:16

+2

@EladBenda:Jon向你展示的是LINQ等價的SQL' top'。 – 2013-04-22 08:20:33

+1

@EladBenda:您特意詢問了有關LINQ to SQL的問題,然後您改變了您的問題。你還說你知道'FirstOrDefault',這與知道'Take'不一樣。如果你打算提出錯誤的問題,你應該期望得到不包括你想要的答案。說實話,即使在實體框架中,我也會使用'Take',除非你真的需要*使用'Top'。當你的問題含糊不清時,它確實無濟於事。 – 2013-04-22 08:23:10

1

請看MSDN爲例http://msdn.microsoft.com/en-GB/library/bb155995.aspx

using (AdventureWorksEntities context = 
    new AdventureWorksEntities()) 
{ 
    string queryString = 
     @"SELECT VALUE product FROM AdventureWorksEntities.Products AS product"; 

    ObjectQuery<Product> productQuery1 = 
     new ObjectQuery<Product>(queryString, context, MergeOption.NoTracking); 

    ObjectQuery<Product> productQuery2 = productQuery1.Top("2"); 

    // Iterate through the collection of Product items. 
    foreach (Product result in productQuery2) 
     Console.WriteLine("{0}", result.Name); 
} 

或者,如果你只是有List<T>考慮使用Take()擴展名。

List<string> strs = new List<strs>() { "1", "2", "3", "4" }; 
var firstTwo = strs.Take(2);