Ejemplos de sintaxis de expresiones de consulta: FiltradoQuery Expression Syntax Examples: Filtering

Los ejemplos de este tema muestran cómo usar el Where y Where…Contains métodos para consultar el modelo AdventureWorks Sales con la sintaxis de expresión de consulta.The examples in this topic demonstrate how to use the Where and Where…Contains methods to query the AdventureWorks Sales Model using query expression syntax. Note, Where…ContainsNote, Where…Contains no se puede usar como parte de un consulta compilada.cannot be used as a part of a compiled query.

El modelo AdventureWorks Sales que se usa en estos ejemplos se crea a partir de las tablas Contact, Address, Product, SalesOrderHeader y SalesOrderDetail en la base de datos de ejemplo AdventureWorks.The AdventureWorks Sales model used in these examples is built from the Contact, Address, Product, SalesOrderHeader, and SalesOrderDetail tables in the AdventureWorks sample database.

Los ejemplos de este tema usan los siguientes using / Imports instrucciones:The examples in this topic use the following using/Imports statements:

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Globalization;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Data.Common;
Option Explicit On
Option Strict On
Imports System.Data.Objects
Imports System.Globalization

WhereWhere

EjemploExample

En el ejemplo siguiente se devuelven todos los pedidos en línea.The following example returns all online orders.

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    var onlineOrders =
        from order in context.SalesOrderHeaders
        where order.OnlineOrderFlag == true
        select new
        {
            SalesOrderID = order.SalesOrderID,
            OrderDate = order.OrderDate,
            SalesOrderNumber = order.SalesOrderNumber
        };

    foreach (var onlineOrder in onlineOrders)
    {
        Console.WriteLine("Order ID: {0} Order date: {1:d} Order number: {2}",
            onlineOrder.SalesOrderID,
            onlineOrder.OrderDate,
            onlineOrder.SalesOrderNumber);
    }
}
Using context As New AdventureWorksEntities
    Dim orders As ObjectSet(Of SalesOrderHeader) = context.SalesOrderHeaders

    Dim onlineOrders = _
        From order In orders _
        Where order.OnlineOrderFlag = True _
        Select New With { _
           .SalesOrderID = order.SalesOrderID, _
           .OrderDate = order.OrderDate, _
           .SalesOrderNumber = order.SalesOrderNumber _
        }

    For Each onlineOrder In onlineOrders
        Console.WriteLine("Order ID: {0} Order date: {1:d} Order number: {2}", _
                onlineOrder.SalesOrderID, _
                onlineOrder.OrderDate, _
                onlineOrder.SalesOrderNumber)
    Next
End Using

EjemploExample

En el ejemplo siguiente se devuelven los pedidos en los que la cantidad de pedido es superior a 2 e inferior a 6.The following example returns the orders where the order quantity is greater than 2 and less than 6.

int orderQtyMin = 2;
int orderQtyMax = 6;
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    var query =
        from order in context.SalesOrderDetails
        where order.OrderQty > orderQtyMin && order.OrderQty < orderQtyMax
        select new
        {
            SalesOrderID = order.SalesOrderID,
            OrderQty = order.OrderQty
        };

    foreach (var order in query)
    {
        Console.WriteLine("Order ID: {0} Order quantity: {1}",
            order.SalesOrderID, order.OrderQty);
    }
}
Dim orderQtyMin = 2
Dim orderQtyMax = 6
Using context As New AdventureWorksEntities
    Dim orders As ObjectSet(Of SalesOrderDetail) = context.SalesOrderDetails

    Dim query = _
        From order In orders _
        Where order.OrderQty > orderQtyMin And order.OrderQty < orderQtyMax _
        Select New With { _
            .SalesOrderID = order.SalesOrderID, _
            .OrderQty = order.OrderQty _
        }

    For Each order In query
        Console.WriteLine("Order ID: {0} Order quantity: {1}", _
                order.SalesOrderID, order.OrderQty)
    Next
End Using

EjemploExample

En el ejemplo siguiente se devuelven todos los productos de color rojo.The following example returns all red colored products.

String color = "Red";
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    var query =
        from product in context.Products
        where product.Color == color
        select new
        {
            Name = product.Name,
            ProductNumber = product.ProductNumber,
            ListPrice = product.ListPrice
        };

    foreach (var product in query)
    {
        Console.WriteLine("Name: {0}", product.Name);
        Console.WriteLine("Product number: {0}", product.ProductNumber);
        Console.WriteLine("List price: ${0}", product.ListPrice);
        Console.WriteLine("");
    }
}
Dim color = "Red"
Using context As New AdventureWorksEntities
    Dim products As ObjectSet(Of Product) = context.Products

    Dim query = _
        From product In products _
        Where product.Color = color _
        Select New With { _
            .Name = product.Name, _
            .ProductNumber = product.ProductNumber, _
            .ListPrice = product.ListPrice _
        }

    For Each product In query
        Console.WriteLine("Name: {0}", product.Name)
        Console.WriteLine("Product number: {0}", product.ProductNumber)
        Console.WriteLine("List price: ${0}", product.ListPrice)
        Console.WriteLine("")
    Next
End Using

EjemploExample

En el ejemplo siguiente se utiliza el método Where para buscar los pedidos que se realizaron después del 1 de diciembre de 2003 y, a continuación, se utiliza la propiedad de navegación order.SalesOrderDetail para obtener los detalles de cada pedido.The following example uses the Where method to find orders that were made after December 1, 2003, and then uses the order.SalesOrderDetail navigation property to get the details for each order.

using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    IQueryable<SalesOrderHeader> query =
        from order in context.SalesOrderHeaders
        where order.OrderDate >= new DateTime(2003, 12, 1)
        select order;


    Console.WriteLine("Orders that were made after December 1, 2003:");
    foreach (SalesOrderHeader order in query)
    {
        Console.WriteLine("OrderID {0} Order date: {1:d} ",
            order.SalesOrderID, order.OrderDate);
        foreach (SalesOrderDetail orderDetail in order.SalesOrderDetails)
        {
            Console.WriteLine("  Product ID: {0} Unit Price {1}",
                orderDetail.ProductID, orderDetail.UnitPrice);
        }
    }
}
Using context As New AdventureWorksEntities
    Dim orders As ObjectSet(Of SalesOrderHeader) = context.SalesOrderHeaders

    Dim query = _
        From order In orders _
        Where order.OrderDate >= New DateTime(2003, 12, 1) _
        Select order

    Console.WriteLine("Orders that were made after December 1, 2003:")
    For Each order In query
        Console.WriteLine("OrderID {0} Order date: {1:d} ", _
                order.SalesOrderID, order.OrderDate)
        For Each orderDetail In order.SalesOrderDetails
            Console.WriteLine("  Product ID: {0} Unit Price {1}", _
                orderDetail.ProductID, orderDetail.UnitPrice)
        Next
    Next
End Using

Where…ContainsWhere…Contains

EjemploExample

En el ejemplo siguiente se usa una matriz como parte de una cláusula Where…Contains para encontrar todos los productos que tienen un ProductModelID que coincide con un valor de la matriz.The following example uses an array as part of a Where…Contains clause to find all products that have a ProductModelID that matches a value in the array.

using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    int?[] productModelIds = {19, 26, 118};
    var products = from p in AWEntities.Products
                   where productModelIds.Contains(p.ProductModelID)
                   select p;
    foreach (var product in products)
    {
        Console.WriteLine("{0}: {1}", product.ProductModelID, product.ProductID);
    }
}
Using AWEntities As New AdventureWorksEntities()
    Dim productModelIds As System.Nullable(Of Integer)() = {19, 26, 118}
    Dim products = From p In AWEntities.Products _
        Where productModelIds.Contains(p.ProductModelID) _
        Select p
    For Each product In products
        Console.WriteLine("{0}: {1}", product.ProductModelID, product.ProductID)
    Next
End Using

Nota

Como parte del predicado de una cláusula Where…Contains, puede utilizar Array, List<T> o una colección de cualquier tipo que implemente la interfaz IEnumerable<T>.As part of the predicate in a Where…Contains clause, you can use an Array, a List<T>, or a collection of any type that implements the IEnumerable<T> interface. También puede declarar e inicializar una colección en una consulta LINQ to Entities.You can also declare and initialize a collection within a LINQ to Entities query. Para obtener más información, vea el ejemplo siguiente.See the next example for more information.

EjemploExample

El ejemplo siguiente declara e inicializa las matrices en una cláusula Where…Contains para encontrar todos los productos que tienen un ProductModelID o Size que coinciden con los valores de las matrices.The following example declares and initializes arrays in a Where…Contains clause to find all products that have a ProductModelID or Size that match values in the arrays.

using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    var products = from p in AWEntities.Products
                   where (new int?[] { 19, 26, 18 }).Contains(p.ProductModelID) ||
                         (new string[] { "L", "XL" }).Contains(p.Size)
                   select p;
    foreach (var product in products)
    {
        Console.WriteLine("{0}: {1}, {2}", product.ProductID, 
                                           product.ProductModelID, 
                                           product.Size);
    }
}
Using AWEntities As New AdventureWorksEntities()
    Dim products = From p In AWEntities.Products _
        Where (New System.Nullable(Of Integer)() {19, 26, 18}).Contains(p.ProductModelID) _
        OrElse (New String() {"L", "XL"}).Contains(p.Size) _
        Select p
    For Each product In products
        Console.WriteLine("{0}: {1}, {2}", product.ProductID, _
                                           product.ProductModelID, _
                                           product.Size)
    Next
End Using

Vea tambiénSee also