Поделиться через


Примеры синтаксиса запросов на основе методов: секционирование (LINQ to Entities)

Примеры в этом разделе демонстрируют, как использовать методы Skip и Take для выполнения запросов к модели AdventureWorks Sales с использованием синтаксиса выражения запроса. Модель AdventureWorks Sales, которая используется в этих примерах, состоит из таблиц Contact, Address, Product, SalesOrderHeader и SalesOrderDetail образца базы данных AdventureWorks.

В примерах, приведенных в этом разделе, используются следующие инструкции using/Imports:

Option Explicit On
Option Strict On
Imports L2EExamplesVB.AdventureWorksModel
Imports System.Data.Objects
Imports System.Globalization
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using AdventureWorksModel;
using System.Globalization;

Дополнительные сведения см. в разделе Как создать проект LINQ to Entities в среде Visual Studio.

Skip

Пример

В следующем примере метод Skip используется для возврата всех контактных лиц в таблице Contact, за исключением первых пяти.

Using AWEntities As New AdventureWorksEntities
    'LINQ to Entities only supports Skip on ordered collections.
    Dim products As IOrderedQueryable(Of Product) = _
            AWEntities.Product.OrderBy(Function(p) p.ListPrice)

    Dim allButFirst3Products As IQueryable(Of Product) = products.Skip(3)

    Console.WriteLine("All but first 3 products:")
    For Each product As Product In allButFirst3Products
        Console.WriteLine("Name: {0} \t ID: {1}", _
                product.Name, _
                product.ProductID)
    Next
End Using
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    // LINQ to Entities only supports Skip on ordered collections.
    IOrderedQueryable<Product> products = AWEntities.Product
            .OrderBy(p => p.ListPrice);

    IQueryable<Product> allButFirst3Products = products.Skip(3);

    Console.WriteLine("All but first 3 products:");
    foreach (Product product in allButFirst3Products)
    {
        Console.WriteLine("Name: {0} \t ID: {1}",
            product.Name,
            product.ProductID);
    }
}

Пример

В следующем примере метод Skip используется для получения всех адресов в Сиэттле, кроме первых двух.

Using AWEntities As New AdventureWorksEntities
    Dim orders As ObjectQuery(Of SalesOrderHeader) = AWEntities.SalesOrderHeader
    Dim addresses As ObjectQuery(Of Address) = AWEntities.Address

    'LINQ to Entities only supports Skip on ordered collections.
    Dim query = ( _
        From address In addresses _
        From order In orders _
        Where address.AddressID = order.Address.AddressID _
                 And address.City = "Seattle" _
        Order By order.SalesOrderID _
        Select New With _
        { _
            .City = address.City, _
            .OrderID = order.SalesOrderID, _
            .OrderDate = order.OrderDate _
        }).Skip(2)

    Console.WriteLine("All but first 2 orders in Seattle:")
    For Each order In query
        Console.WriteLine("City: {0} Order ID: {1} Total Due: {2:d}", _
            order.City, order.OrderID, order.OrderDate)
    Next
End Using
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectQuery<Address> addresses = AWEntities.Address;
    ObjectQuery<SalesOrderHeader> orders = AWEntities.SalesOrderHeader;

    //LINQ to Entities only supports Skip on ordered collections.
    var query = (
        from address in addresses
        from order in orders
        where address.AddressID == order.Address.AddressID
             && address.City == "Seattle"
        orderby order.SalesOrderID
        select new
        {
            City = address.City,
            OrderID = order.SalesOrderID,
            OrderDate = order.OrderDate
        }).Skip(2);

    Console.WriteLine("All but first 2 orders in Seattle:");
    foreach (var order in query)
    {
        Console.WriteLine("City: {0} Order ID: {1} Total Due: {2:d}",
            order.City, order.OrderID, order.OrderDate);
    }

Take

Пример

В следующем примере метод Take используется для возврата первых пяти контактных лиц из таблицы Contact.

Using AWEntities As New AdventureWorksEntities
    Dim contacts As ObjectQuery(Of Contact) = AWEntities.Contact

    Dim first5Contacts As IQueryable(Of Contact) = contacts.Take(5)

    Console.WriteLine("First 5 contacts:")
    For Each contact As Contact In first5Contacts
        Console.WriteLine("Title = {0} " & vbTab & " FirstName = {1} " _
            & vbTab & " Lastname = {2}", contact.Title, contact.FirstName, _
            contact.LastName)
    Next
End Using
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectQuery<Contact> contacts = AWEntities.Contact;

    IQueryable<Contact> first5Contacts = contacts.Take(5);

    Console.WriteLine("First 5 contacts:");
    foreach (Contact contact in first5Contacts)
    {
        Console.WriteLine("Title = {0} \t FirstName = {1} \t Lastname = {2}",
            contact.Title,
            contact.FirstName,
            contact.LastName);
    }
}

Пример

В следующем примере метод Take используется для получения первых трех адресов в Сиэттле.

Using AWEntities As New AdventureWorksEntities
    Dim orders As ObjectQuery(Of SalesOrderHeader) = AWEntities.SalesOrderHeader
    Dim addresses As ObjectQuery(Of Address) = AWEntities.Address

    Dim query = ( _
        From address In addresses _
        From order In orders _
        Where address.AddressID = order.Address.AddressID _
                 And address.City = "Seattle" _
        Select New With _
        { _
            .City = address.City, _
            .OrderID = order.SalesOrderID, _
            .OrderDate = order.OrderDate _
        }).Take(3)

    Console.WriteLine("First 3 orders in Seattle:")
    For Each order In query
        Console.WriteLine("City: {0} Order ID: {1} Total Due: {2:d}", _
            order.City, order.OrderID, order.OrderDate)
    Next
End Using
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    ObjectQuery<Address> addresses = AWEntities.Address;
    ObjectQuery<SalesOrderHeader> orders = AWEntities.SalesOrderHeader;

    var query = (
        from address in addresses
        from order in orders
        where address.AddressID == order.Address.AddressID
             && address.City == "Seattle"
        select new
        {
            City = address.City,
            OrderID = order.SalesOrderID,
            OrderDate = order.OrderDate
        }).Take(3);
    Console.WriteLine("First 3 orders in Seattle:");
    foreach (var order in query)
    {
        Console.WriteLine("City: {0} Order ID: {1} Total Due: {2:d}",
            order.City, order.OrderID, order.OrderDate);
    }
}

См. также

Основные понятия

Примеры синтаксиса запросов на базе методов (LINQ to Entities)