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.ListPrice排序)后获取五Product个对象。 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 具有不确定性。

在 方法之后Skip使用 Top 方法时,它的函数类似于 ORDER BY 子句的 LIMIT 语句。

适用于

另请参阅