Friday, October 4, 2019

C# - How to join two LINQ dataset

This example join COUNTRY with CONTINENT; and shows CONTINENT where exists COUNTRY with population greater than 300.

/* -- declare class */

public class Country {
  public string Name;
  public string ContinentName;
  public int Population;

  public Country( string _name, string _continentName, int _population ) {
    this.Name = _name;
    this.ContinentName = _continentName;
    this.Population = _population;
  }
}

/* -- init */

List<country> listCountry = new List();

listCountry.Add( new Country( "czech", "europe", 10 ) );
listCountry.Add( new Country( "germany", "europe", 60 ) );
listCountry.Add( new Country( "france", "europe", 60 ) );
listCountry.Add( new Country( "usa", "america", 350 ) );
listCountry.Add( new Country( "china", "asia", 1200 ) );

/* -- join */

List listContinent = new List();

listContinent.Add( new Continent( "europe", 1 ) );
listContinent.Add( new Continent( "america", 2 ) );
listContinent.Add( new Continent( "asia", 3 ) );

var list = ( from rowCountry in listCountry join rowContinent in listContinent
             on rowCountry.ContinentName equals rowContinent.ContinentName
             where
             rowCountry.Population > 300
             select new {
               Name = rowCountry.Name,                     
               RelationField = rowContinent.RelationField
             } );

foreach ( var row in list ) 
  Console.WriteLine( 
    string.Format( "ContinentName = {0} RelationField={1} ", row.Name, row.RelationField ) );
      
Console.WriteLine();
Output:
ContinentName = usa RelationField=2 
ContinentName = china RelationField=3