다음을 통해 공유


메서드 기반 쿼리 구문 예제: 조인(LINQ to DataSet)

조인은 관계형 데이터베이스 테이블과 같이 서로 탐색할 수 없는 관계를 가진 데이터 소스를 대상으로 하는 쿼리에 사용되는 중요한 작업입니다. 두 데이터 소스를 조인하는 것은 한 데이터 소스의 개체를 공통 특성을 공유하는 다른 데이터 소스의 개체와 연결하는 것입니다. 자세한 내용은 표준 쿼리 연산자 개요(C#) 또는 표준 쿼리 연산자 개요(Visual Basic)를 참조하세요.

이 항목의 예제에서는 Join 메서드에서 메서드 쿼리 구문을 사용하여 DataSet을 쿼리하는 방법을 보여 줍니다.

이러한 예제에서 사용되는 FillDataSet 메서드는 데이터집합에 데이터를 로드하는데 지정됩니다.

이 항목의 예제에서는 AdventureWorks 샘플 데이터베이스의 Contact, Address, Product, SalesOrderHeader 및 SalesOrderDetail 테이블을 사용합니다.

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

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
Option Explicit On

Imports System.Linq
Imports System.Linq.Expressions
Imports System.Collections.Generic
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.Common
Imports System.Globalization

자세한 내용은 방법: Visual Studio에서 LINQ to DataSet 프로젝트 만들기를 참조하세요.

Join

예시

이 예제에서는 ContactSalesOrderHeader 테이블에 대한 조인을 수행합니다.

// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);

DataTable contacts = ds.Tables["Contact"];
DataTable orders = ds.Tables["SalesOrderHeader"];

var query =
    contacts.AsEnumerable().Join(orders.AsEnumerable(),
    order => order.Field<Int32>("ContactID"),
    contact => contact.Field<Int32>("ContactID"),
    (contact, order) => new
    {
        ContactID = contact.Field<Int32>("ContactID"),
        SalesOrderID = order.Field<Int32>("SalesOrderID"),
        FirstName = contact.Field<string>("FirstName"),
        Lastname = contact.Field<string>("Lastname"),
        TotalDue = order.Field<decimal>("TotalDue")
    });

foreach (var contact_order in query)
{
    Console.WriteLine("ContactID: {0} "
                    + "SalesOrderID: {1} "
                    + "FirstName: {2} "
                    + "Lastname: {3} "
                    + "TotalDue: {4}",
        contact_order.ContactID,
        contact_order.SalesOrderID,
        contact_order.FirstName,
        contact_order.Lastname,
        contact_order.TotalDue);
}
' Fill the DataSet.
Dim ds As New DataSet()
ds.Locale = CultureInfo.InvariantCulture
' See the FillDataSet method in the Loading Data Into a DataSet topic.
FillDataSet(ds)

Dim contacts As DataTable = ds.Tables("Contact")
Dim orders As DataTable = ds.Tables("SalesOrderHeader")

Dim query = _
    contacts.AsEnumerable().Join(orders.AsEnumerable(), _
    Function(order) order.Field(Of Int32)("ContactID"), _
    Function(contact) contact.Field(Of Int32)("ContactID"), _
    Function(contact, order) New With _
        { _
            .ContactID = contact.Field(Of Int32)("ContactID"), _
            .SalesOrderID = order.Field(Of Int32)("SalesOrderID"), _
            .FirstName = contact.Field(Of String)("FirstName"), _
            .Lastname = contact.Field(Of String)("Lastname"), _
            .TotalDue = order.Field(Of Decimal)("TotalDue") _
        })

For Each contact_order In query
    Console.WriteLine("ContactID: {0} " _
                    & "SalesOrderID: {1} " _
                    & "FirstName: {2} " _
                    & "Lastname: {3} " _
                    & "TotalDue: {4}", _
        contact_order.ContactID, _
        contact_order.SalesOrderID, _
        contact_order.FirstName, _
        contact_order.Lastname, _
        contact_order.TotalDue)
Next

예시

이 예제에서는 ContactSalesOrderHeader 테이블에 대한 조인을 수행하고 연락처 ID별로 결과를 그룹화합니다.

// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);

DataTable contacts = ds.Tables["Contact"];
DataTable orders = ds.Tables["SalesOrderHeader"];

var query = contacts.AsEnumerable().Join(orders.AsEnumerable(),
    order => order.Field<Int32>("ContactID"),
    contact => contact.Field<Int32>("ContactID"),
    (contact, order) => new
    {
        ContactID = contact.Field<Int32>("ContactID"),
        SalesOrderID = order.Field<Int32>("SalesOrderID"),
        FirstName = contact.Field<string>("FirstName"),
        Lastname = contact.Field<string>("Lastname"),
        TotalDue = order.Field<decimal>("TotalDue")
    })
        .GroupBy(record => record.ContactID);

foreach (var group in query)
{
    foreach (var contact_order in group)
    {
        Console.WriteLine("ContactID: {0} "
                        + "SalesOrderID: {1} "
                        + "FirstName: {2} "
                        + "Lastname: {3} "
                        + "TotalDue: {4}",
            contact_order.ContactID,
            contact_order.SalesOrderID,
            contact_order.FirstName,
            contact_order.Lastname,
            contact_order.TotalDue);
    }
}
' Fill the DataSet.
Dim ds As New DataSet()
ds.Locale = CultureInfo.InvariantCulture
' See the FillDataSet method in the Loading Data Into a DataSet topic.
FillDataSet(ds)

Dim contacts As DataTable = ds.Tables("Contact")
Dim orders As DataTable = ds.Tables("SalesOrderHeader")

Dim query = _
    contacts.AsEnumerable().Join(orders.AsEnumerable(), _
    Function(order) order.Field(Of Int32)("ContactID"), _
    Function(contact) contact.Field(Of Int32)("ContactID"), _
        Function(contact, order) New With _
        { _
            .ContactID = contact.Field(Of Int32)("ContactID"), _
            .SalesOrderID = order.Field(Of Int32)("SalesOrderID"), _
            .FirstName = contact.Field(Of String)("FirstName"), _
            .Lastname = contact.Field(Of String)("Lastname"), _
            .TotalDue = order.Field(Of Decimal)("TotalDue") _
        }) _
        .GroupBy(Function(record) record.ContactID)

For Each group In query
    For Each contact_order In group
        Console.WriteLine("ContactID: {0} " _
                        & "SalesOrderID: {1} " _
                        & "FirstName: {2} " _
                        & "Lastname: {3} " _
                        & "TotalDue: {4}", _
            contact_order.ContactID, _
            contact_order.SalesOrderID, _
            contact_order.FirstName, _
            contact_order.Lastname, _
            contact_order.TotalDue)
    Next
Next

참고 항목