C# Enumerable GroupJoin(IEnumerable, IEnumerable, Func, Func, Func, TResult>)

Description

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

Syntax


public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(
  this IEnumerable<TOuter> outer,
  IEnumerable<TInner> inner,//w  ww  .j  a v a  2 s.c o m
  Func<TOuter, TKey> outerKeySelector,
  Func<TInner, TKey> innerKeySelector,
  Func<TOuter, IEnumerable<TInner>, TResult> resultSelector
)

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.
  • outer - The first sequence to join.
  • inner - The sequence to join to the first sequence.
  • outerKeySelector - A function to extract the join key from each element of the first sequence.
  • innerKeySelector - A function to extract the join key from each element of the second sequence.
  • resultSelector - A function to create a result element from an element from the first sequence and a collection of matching elements from the second sequence.

Example

The following code example demonstrates how to use GroupJoin to perform a grouped join on two sequences.


/*from   w  w w.j  a  v  a 2 s.co  m*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
     Person magnus = new Person { Name = "A" };
     Person terry = new Person { Name = "B" };
     Person charlotte = new Person { Name = "C" };

     Pet petA = new Pet { Name = "D", Owner = terry };
     Pet petB = new Pet { Name = "E", Owner = terry };
     Pet petC = new Pet { Name = "F", Owner = charlotte };
     Pet petD = new Pet { Name = "G", Owner = magnus };

     List<Person> people = new List<Person> { magnus, terry, charlotte };
     List<Pet> pets = new List<Pet> { petA, petB, petC, petD };

     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)
     {
         Console.WriteLine("{0}:", obj.OwnerName);
         foreach (string pet in obj.Pets)
         {
             Console.WriteLine("  {0}", pet);
         }
     }

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




















Home »
  C# Tutorial »
    System.Linq »




Enumerable