다음을 통해 공유


방법: 조인을 사용하여 LINQ와 데이터 결합(Visual Basic)

Visual Basic은 컬렉션 간의 공통 값을 기반으로 여러 컬렉션의 콘텐츠를 결합할 수 있도록 하는 쿼리 절과 Join 쿼리 절을 제공합니다Group Join. 이러한 값을 값이라고 합니다. 관계형 데이터베이스 개념에 익숙한 개발자는 Join 절을 INNER JOIN으로, 그리고 Group Join 절을 사실상 LEFT OUTER JOIN으로 인식할 것입니다.

이 항목의 예제에서는 JoinGroup Join 쿼리 절을 사용하여 데이터를 결합하는 몇 가지 방법을 보여 줍니다.

프로젝트 만들기 및 샘플 데이터 추가

샘플 데이터 및 형식이 포함된 프로젝트를 만들려면

  1. 이 항목의 샘플을 실행하려면 Visual Studio를 열고 새 Visual Basic 콘솔 애플리케이션 프로젝트를 추가합니다. Visual Basic에서 만든 Module1.vb 파일을 두 번 클릭합니다.

  2. 이 항목의 샘플은 다음 코드 예제의 PersonPet 형식 및 데이터를 사용합니다. Visual Basic에서 만든 기본 Module1 모듈에 이 코드를 복사합니다.

    Private _people As List(Of Person)
    Private _pets As List(Of Pet)
    
    Function GetPeople() As List(Of Person)
        If _people Is Nothing Then CreateLists()
        Return _people
    End Function
    
    Function GetPets(ByVal people As List(Of Person)) As List(Of Pet)
        If _pets Is Nothing Then CreateLists()
        Return _pets
    End Function
    
    Private Sub CreateLists()
        Dim pers As Person
    
        _people = New List(Of Person)
        _pets = New List(Of Pet)
    
        pers = New Person With {.FirstName = "Magnus", .LastName = "Hedlund"}
        _people.Add(pers)
        _pets.Add(New Pet With {.Name = "Daisy", .Owner = pers})
    
        pers = New Person With {.FirstName = "Terry", .LastName = "Adams"}
        _people.Add(pers)
        _pets.Add(New Pet With {.Name = "Barley", .Owner = pers})
        _pets.Add(New Pet With {.Name = "Boots", .Owner = pers})
        _pets.Add(New Pet With {.Name = "Blue Moon", .Owner = pers})
    
        pers = New Person With {.FirstName = "Charlotte", .LastName = "Weiss"}
        _people.Add(pers)
        _pets.Add(New Pet With {.Name = "Whiskers", .Owner = pers})
    
        ' Add a person with no pets for the sake of Join examples.
        _people.Add(New Person With {.FirstName = "Arlene", .LastName = "Huff"})
    
        pers = New Person With {.FirstName = "Don", .LastName = "Hall"}
        ' Do not add person to people list for the sake of Join examples.
        _pets.Add(New Pet With {.Name = "Spot", .Owner = pers})
    
        ' Add a pet with no owner for the sake of Join examples.
        _pets.Add(New Pet With {.Name = "Unknown",
                                .Owner = New Person With {.FirstName = String.Empty,
                                                          .LastName = String.Empty}})
    End Sub
    
    Class Person
        Public Property FirstName As String
        Public Property LastName As String
    End Class
    
    Class Pet
        Public Property Name As String
        Public Property Owner As Person
    End Class
    

Join 절을 사용하여 내부 조인을 수행합니다.

INNER JOIN은 두 컬렉션의 데이터를 결합합니다. 지정된 키 값이 일치하는 항목이 포함됩니다. 다른 컬렉션에 일치하는 항목이 없는 컬렉션의 모든 항목은 제외됩니다.

Visual Basic에서 LINQ는 INNER JOIN을 수행하기 위한 두 가지 옵션인 암시적 조인과 명시적 조인을 제공합니다.

암시적 조인은 From 절에서 조인할 컬렉션을 지정하고 Where 절에서 키 필드를 식별하여 일치시킵니다. Visual Basic은 지정된 키 필드에 따라 두 컬렉션을 암시적으로 조인합니다.

조인에서 사용할 키 필드를 구체적으로 지정하려면 절을 사용하여 Join 명시적 조인을 지정할 수 있습니다. 이 경우 절을 Where 사용하여 쿼리 결과를 필터링할 수 있습니다.

내부 조인을 수행하려면 Join 절을 사용하십시오.

  1. 프로젝트의 모듈에 Module1 다음 코드를 추가하여 암시적 조인과 명시적 내부 조인의 예제를 확인합니다.

    Sub InnerJoinExample()
        ' Create two lists.
        Dim people = GetPeople()
        Dim pets = GetPets(people)
    
        ' Implicit Join.
        Dim petOwners = From pers In people, pet In pets
                        Where pet.Owner Is pers
                        Select pers.FirstName, PetName = pet.Name
    
        ' Display grouped results.
        Dim output As New System.Text.StringBuilder
        For Each pers In petOwners
            output.AppendFormat(
              pers.FirstName & ":" & vbTab & pers.PetName & vbCrLf)
        Next
    
        Console.WriteLine(output)
    
        ' Explicit Join.
        Dim petOwnersJoin = From pers In people
                            Join pet In pets
                            On pet.Owner Equals pers
                            Select pers.FirstName, PetName = pet.Name
    
        ' Display grouped results.
        output = New System.Text.StringBuilder()
        For Each pers In petOwnersJoin
            output.AppendFormat(
              pers.FirstName & ":" & vbTab & pers.PetName & vbCrLf)
        Next
    
        Console.WriteLine(output)
    
        ' Both queries produce the following output:
        '
        ' Magnus:    Daisy
        ' Terry:     Barley
        ' Terry:     Boots
        ' Terry:     Blue Moon
        ' Charlotte: Whiskers
    End Sub
    

그룹 조인 절을 사용하여 왼쪽 외부 조인을 실행합니다.

LEFT OUTER JOIN에는 조인의 왼쪽 컬렉션에 있는 모든 항목과 조인의 오른쪽 컬렉션에서 일치하는 값만 포함됩니다. 왼쪽 컬렉션에 일치하는 항목이 없는 조인의 오른쪽 컬렉션에 있는 모든 항목은 쿼리 결과에서 제외됩니다.

이 절은 Group Join 사실상 LEFT OUTER JOIN을 수행합니다. 일반적으로 LEFT OUTER JOIN이라고 하는 것과 Group Join 절이 반환하는 것의 차이점은, Group Join 절이 왼쪽 컬렉션에 있는 각 항목에 대해 조인의 오른쪽 컬렉션의 결과를 그룹화한다는 점입니다. 관계형 데이터베이스에서 LEFT OUTER JOIN은 쿼리 결과의 각 항목에 조인의 두 컬렉션에서 일치하는 항목이 포함된 그룹화되지 않은 결과를 반환합니다. 이 경우 조인의 왼쪽 컬렉션에 있는 항목은 오른쪽 컬렉션에서 일치하는 각 항목에 대해 반복됩니다. 다음 절차를 완료하면 어떻게 표시되는지 확인할 수 있습니다.

그룹화된 각 쿼리 결과에 Group Join 대한 항목을 반환하도록 쿼리를 확장하여 쿼리 결과를 그룹화되지 않은 결과로 검색할 수 있습니다. 이렇게 하려면 그룹화된 컬렉션의 메서드를 사용하여 쿼리를 실행해야 합니다. 이렇게 하면 오른쪽 컬렉션에서 일치하는 결과가 없더라도 조인의 왼쪽 컬렉션에 있는 항목이 쿼리 결과에 계속 포함됩니다. 조인의 오른쪽 컬렉션에서 일치하는 값이 없는 경우 쿼리에 코드를 추가하여 기본 결과 값을 제공할 수 있습니다.

그룹 조인 절을 사용하여 왼쪽 외부 조인 작업을 수행하려면

  1. 프로젝트의 모듈에 다음 코드를 Module1 추가하여 그룹화된 왼쪽 외부 조인과 그룹화되지 않은 왼쪽 외부 조인의 예를 확인합니다.

    Sub LeftOuterJoinExample()
        ' Create two lists.
        Dim people = GetPeople()
        Dim pets = GetPets(people)
    
        ' Grouped results.
        Dim petOwnersGrouped = From pers In people
                               Group Join pet In pets
                                 On pers Equals pet.Owner
                               Into PetList = Group
                               Select pers.FirstName, pers.LastName,
                                      PetList
    
        ' Display grouped results.
        Dim output As New System.Text.StringBuilder
        For Each pers In petOwnersGrouped
            output.AppendFormat(pers.FirstName & ":" & vbCrLf)
            For Each pt In pers.PetList
                output.AppendFormat(vbTab & pt.Name & vbCrLf)
            Next
        Next
    
        Console.WriteLine(output)
        ' This code produces the following output:
        '
        ' Magnus:
        '     Daisy
        ' Terry:
        '     Barley
        '     Boots
        '     Blue Moon
        ' Charlotte:
        '     Whiskers
        ' Arlene:
    
        ' "Flat" results.
        Dim petOwners = From pers In people
                        Group Join pet In pets On pers Equals pet.Owner
                        Into PetList = Group
                        From pet In PetList.DefaultIfEmpty()
                        Select pers.FirstName, pers.LastName,
                               PetName =
                                 If(pet Is Nothing, String.Empty, pet.Name)
    
    
        ' Display "flat" results.
        output = New System.Text.StringBuilder()
        For Each pers In petOwners
            output.AppendFormat(
              pers.FirstName & ":" & vbTab & pers.PetName & vbCrLf)
        Next
    
        Console.WriteLine(output.ToString())
        ' This code produces the following output:
        '
        ' Magnus:	    Daisy
        ' Terry:	    Barley
        ' Terry:	    Boots
        ' Terry:	    Blue Moon
        ' Charlotte:	Whiskers
        ' Arlene:	  
    End Sub
    

복합 키를 사용하여 조인 수행

And 키워드를 Join 절 또는 Group Join 절에서 사용하여 조인되는 컬렉션의 값을 일치시킬 여러 키 필드를 식별할 수 있습니다. 키워드는 And 조인할 항목에 대해 지정된 모든 키 필드가 일치하도록 지정합니다.

복합 키를 사용하여 조인을 수행하려면

  1. 프로젝트의 모듈에 Module1 다음 코드를 추가하여 복합 키를 사용하는 조인의 예를 확인합니다.

    Sub CompositeKeyJoinExample()
        ' Create two lists.
        Dim people = GetPeople()
        Dim pets = GetPets(people)
    
        ' Implicit Join.
        Dim petOwners = From pers In people
                        Join pet In pets On
                          pet.Owner.FirstName Equals pers.FirstName And
                          pet.Owner.LastName Equals pers.LastName
                        Select pers.FirstName, PetName = pet.Name
    
        ' Display grouped results.
        Dim output As New System.Text.StringBuilder
        For Each pers In petOwners
            output.AppendFormat(
              pers.FirstName & ":" & vbTab & pers.PetName & vbCrLf)
        Next
    
        Console.WriteLine(output)
        ' This code produces the following output:
        '
        ' Magnus:    Daisy
        ' Terry:     Barley
        ' Terry:     Boots
        ' Terry:     Blue Moon
        ' Charlotte: Whiskers
    End Sub
    

코드 실행

예제를 실행하는 코드를 추가하려면

  1. 프로젝트의 Sub Main 모듈에서 Module1을(를) 다음 코드로 교체하여 이 항목의 예제를 실행하세요.

    Sub Main()
        InnerJoinExample()
        LeftOuterJoinExample()
        CompositeKeyJoinExample()
    
        Console.ReadLine()
    End Sub
    
  2. F5 키를 눌러 예제를 실행합니다.

참고하십시오