C# Enumerable Join(IEnumerable, IEnumerable, Func, Func, Func)

Description

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

Syntax


public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(
  this IEnumerable<TOuter> outer,
  IEnumerable<TInner> inner,/*  ww w.ja  v a  2s .c o  m*/
  Func<TOuter, TKey> outerKeySelector,
  Func<TInner, TKey> innerKeySelector,
  Func<TOuter, 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 two matching elements.

Example

The following code example demonstrates how to use Join to perform an inner join of two sequences based on a common key.


/*  www  . jav a 2 s. com*/
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 barley = new Pet { Name = "D", Owner = terry };
     Pet boots = new Pet { Name = "E", Owner = terry };
     Pet whiskers = new Pet { Name = "F", Owner = charlotte };
     Pet daisy = new Pet { Name = "G", Owner = magnus };

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

     var query =
         people.Join(pets,
                     person => person,
                     pet => pet.Owner,
                     (person, pet) =>
                         new { OwnerName = person.Name, Pet = pet.Name });

     foreach (var obj in query)
     {
         Console.WriteLine(
             "{0} - {1}",
             obj.OwnerName,
             obj.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