다음을 통해 공유


쿼리 식 구문 예제: 필터링(LINQ to Entities)

이 항목의 예제에서는 쿼리 식 구문을 사용하여 AdventureWorks Sales 모델을 쿼리하기 위해 Where and Where…Contains 메서드를 사용하는 방법을 보여 줍니다. Where…Contains컴파일된 쿼리의 일부로 사용할 수 없습니다.

이 예제에서 사용하는 AdventureWorks Sales 모델은 AdventureWorks 샘플 데이터베이스의 Contact, Address, Product, SalesOrderHeader 및 SalesOrderDetail 테이블로 작성되었습니다.

이 항목의 예제에서는 다음 using/Imports 문을 사용합니다.

Option Explicit On
Option Strict On
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 System.Globalization;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Data.Common;

Where

예제

다음 예제에서는 모든 온라인 주문을 반환합니다.

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

예제

다음 예제에서는 주문 수량이 2보다 크고 6보다 작은 주문을 반환합니다.

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

예제

다음 예제에서는 Where 메서드를 사용하여 2003년 12월 1일 이후의 주문을 찾은 다음 order.SalesOrderDetail 탐색 속성을 사용하여 각 주문의 세부 사항을 가져옵니다.

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

Where…Contains

예제

다음 예제에서는 배열을 Where…Contains 절의 일부로 사용하여 ProductModelID가 배열의 값과 일치하는 모든 제품을 찾습니다.

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
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);
    }
}
Bb738636.note(ko-kr,VS.100).gif참고:
Where…Contains 절에 있는 조건자의 일부로 Array, List 또는 IEnumerable 인터페이스를 구현하는 형식의 컬렉션을 사용할 수 있습니다.LINQ to Entities 쿼리 내에서 컬렉션을 선언하고 초기화할 수도 있습니다.자세한 내용은 다음 예제를 참조하십시오.

예제

다음 예제에서는 배열을 Where…Contains 절에서 선언하고 초기화하여 ProductModelID 또는 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
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);
    }
}

참고 항목

개념

LINQ to Entities의 쿼리