Freigeben über


Enumerable.GroupJoin<TOuter, TInner, TKey, TResult> Method (IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter, TKey>, Func<TInner, TKey>, Func<TOuter, IEnumerable<TInner>, TResult>)

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Correlates the elements of two sequences based on equality of keys and groups the results. The default equality comparer is used to compare keys.

Namespace:  System.Linq
Assembly:  System.Core (in System.Core.dll)

Syntax

'Declaration
<ExtensionAttribute> _
Public Shared Function GroupJoin(Of TOuter, TInner, TKey, TResult) ( _
    outer As IEnumerable(Of TOuter), _
    inner As IEnumerable(Of TInner), _
    outerKeySelector As Func(Of TOuter, TKey), _
    innerKeySelector As Func(Of TInner, TKey), _
    resultSelector As Func(Of TOuter, IEnumerable(Of TInner), TResult) _
) As IEnumerable(Of TResult)
public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(
    this IEnumerable<TOuter> outer,
    IEnumerable<TInner> inner,
    Func<TOuter, TKey> outerKeySelector,
    Func<TInner, TKey> innerKeySelector,
    Func<TOuter, IEnumerable<TInner>, TResult> resultSelector
)

Type Parameters

  • TOuter
    The type of the elements of the first sequence.
  • TInner
    The type of the elements of the second sequence.
  • TKey
    The type of the keys returned by the key selector functions.
  • TResult
    The type of the result elements.

Parameters

  • outerKeySelector
    Type: System.Func<TOuter, TKey>
    A function to extract the join key from each element of the first sequence.
  • innerKeySelector
    Type: System.Func<TInner, TKey>
    A function to extract the join key from each element of the second sequence.
  • resultSelector
    Type: System.Func<TOuter, IEnumerable<TInner>, TResult>
    A function to create a result element from an element from the first sequence and a collection of matching elements from the second sequence.

Return Value

Type: System.Collections.Generic.IEnumerable<TResult>
An IEnumerable<T> that contains elements of type TResult that are obtained by performing a grouped join on two sequences.

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type IEnumerable<TOuter>. When you use instance method syntax to call this method, omit the first parameter.

Exceptions

Exception Condition
ArgumentNullException

outer or inner or outerKeySelector or innerKeySelector or resultSelector is nulla null reference (Nothing in Visual Basic).

Remarks

This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic.

The default equality comparer, Default, is used to hash and compare keys.

GroupJoin produces hierarchical results, which means that elements from outer are paired with collections of matching elements from inner. GroupJoin enables you to base your results on a whole set of matches for each element of outer.

NoteNote:

If there are no correlated elements in inner for a given element of outer, the sequence of matches for that element will be empty but will still appear in the results.

The resultSelector function is called only one time for each outer element together with a collection of all the inner elements that match the outer element. This differs from the Join method, in which the result selector function is invoked on pairs that contain one element from outer and one element from inner.

GroupJoin preserves the order of the elements of outer, and for each element of outer, the order of the matching elements from inner.

GroupJoin has no direct equivalent in traditional relational database terms. However, this method does implement a superset of inner joins and left outer joins. Both of these operations can be written in terms of a grouped join.

In query expression syntax, a join … into (Visual C#) or Group Join (Visual Basic) clause translates to an invocation of GroupJoin.

Examples

The following code example demonstrates how to use GroupJoin<TOuter, TInner, TKey, TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter, TKey>, Func<TInner, TKey>, Func<TOuter, IEnumerable<TInner>, TResult>) to perform a grouped join on two sequences.

   Structure Person
      Public Name As String
   End Structure

   Structure Pet
      Public Name As String
      Public Owner As Person
   End Structure

   Sub GroupJoinEx1()
      Dim magnus As New Person With {.Name = "Hedlund, Magnus"}
      Dim terry As New Person With {.Name = "Adams, Terry"}
      Dim charlotte As New Person With {.Name = "Weiss, Charlotte"}

      Dim barley As New Pet With {.Name = "Barley", .Owner = terry}
      Dim boots As New Pet With {.Name = "Boots", .Owner = terry}
      Dim whiskers As New Pet With {.Name = "Whiskers", .Owner = charlotte}
      Dim daisy As New Pet With {.Name = "Daisy", .Owner = magnus}

      Dim people As New List(Of Person)(New Person() {magnus, terry, charlotte})
      Dim pets As New List(Of Pet)(New Pet() {barley, boots, whiskers, daisy})

      ' Create a collection where each element is an anonymous type
      ' that contains a Person's name and a collection of names of 
      ' the pets that are owned by them.
      Dim query = _
          people.GroupJoin(pets, _
                     Function(person) person, _
                     Function(pet) pet.Owner, _
                     Function(person, petCollection) _
                         New With {.OwnerName = person.Name, _
                                   .Pets = petCollection.Select( _
                                                      Function(pet) pet.Name)})

      Dim output As New System.Text.StringBuilder
      For Each obj In query
         ' Output the owner's name.
         output.AppendLine(obj.OwnerName & ":")
         ' Output each of the owner's pet's names.
         For Each pet As String In obj.Pets
            output.AppendLine("  " & pet)
         Next
      Next

      ' Display the output.
      outputBlock.Text &= output.ToString() & vbCrLf
   End Sub

   ' This code produces the following output:
   '
   ' Hedlund, Magnus
   '   Daisy
   ' Adams, Terry
   '   Barley
   '   Boots
   ' Weiss, Charlotte
   '   Whiskers

      class Person
      {
         public string Name { get; set; }
      }

      class Pet
      {
         public string Name { get; set; }
         public Person Owner { get; set; }
      }

      public static void GroupJoinEx1()
      {
         Person magnus = new Person { Name = "Hedlund, Magnus" };
         Person terry = new Person { Name = "Adams, Terry" };
         Person charlotte = new Person { Name = "Weiss, Charlotte" };

         Pet barley = new Pet { Name = "Barley", Owner = terry };
         Pet boots = new Pet { Name = "Boots", Owner = terry };
         Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };
         Pet daisy = new Pet { Name = "Daisy", Owner = magnus };

         List<Person> people = new List<Person> { magnus, terry, charlotte };
         List<Pet> pets = new List<Pet> { barley, boots, whiskers, daisy };

         // Create a list where each element is an anonymous 
         // type that contains a person's name and 
         // a collection of names of the pets they own.
         var query =
             people.GroupJoin(pets,
                              person => person,
                              pet => pet.Owner,
                              (person, petCollection) =>
                                  new
                                  {
                                     OwnerName = person.Name,
                                     Pets = petCollection.Select(pet => pet.Name)
                                  });

         foreach (var obj in query)
         {
            // Output the owner's name.
            outputBlock.Text += String.Format("{0}:", obj.OwnerName) + "\n";
            // Output each of the owner's pet's names.
            foreach (string pet in obj.Pets)
            {
               outputBlock.Text += String.Format("  {0}", pet) + "\n";
            }
         }
      }

      /*
       This code produces the following output:

       Hedlund, Magnus:
         Daisy
       Adams, Terry:
         Barley
         Boots
       Weiss, Charlotte:
         Whiskers
      */

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.