ObjectQuery<T>.Top(String, ObjectParameter[]) 方法

定義

將查詢結果限制為指定的項目數。

public:
 System::Data::Objects::ObjectQuery<T> ^ Top(System::String ^ count, ... cli::array <System::Data::Objects::ObjectParameter ^> ^ parameters);
public System.Data.Objects.ObjectQuery<T> Top (string count, params System.Data.Objects.ObjectParameter[] parameters);
member this.Top : string * System.Data.Objects.ObjectParameter[] -> System.Data.Objects.ObjectQuery<'T>
Public Function Top (count As String, ParamArray parameters As ObjectParameter()) As ObjectQuery(Of T)

參數

count
String

結果中的項目數 (成為字串)。

parameters
ObjectParameter[]

一組選擇性查詢參數,而且這些參數在剖析時應該位於範圍中。

傳回

新的 ObjectQuery<T> 執行個體,它就相當於套用了 TOP 的原始執行個體。

例外狀況

countnull

count 為空字串。

範例

這個範例會建立新的 ObjectQuery<T>,其中包含現有查詢的前兩個結果。

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

這個範例會在略過查詢結果中的前三個對象之後取得五 Product 個 物件,並依 Product.ListPrice排序。 Top 會用於分頁,而不是 LIMIT

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    // Define the parameters used to define the "page" of returned data.
    int skipValue = 3;
    int limitValue = 5;

    // Define a query that returns a "page" or the full
    // Product data using the Skip and Top methods.
    // When Top() follows Skip(), it acts like the LIMIT statement.
    ObjectQuery<Product> query = context.Products
        .Skip("it.ListPrice", "@skip",
                new ObjectParameter("skip", skipValue))
        .Top("@limit", new ObjectParameter("limit", limitValue));

    // Iterate through the page of Product items.
    foreach (Product result in query)
        Console.WriteLine("ID: {0}; Name: {1}",
        result.ProductID, result.Name);
}

備註

除非查詢已排序,否則 Top 不具決定性。

當您在 Top 方法之後使用 方法時Skip,它會像 ORDER BY 子句的 LIMIT 語句一樣運作。

適用於

另請參閱