Thursday, August 22, 2019

C# - How to use IEnumerable interface with LINQ

/* -- 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 ) );

/* -- IEnumerable -> list of europe items */

IEnumerable<country> europeList = 
  from row in listCountry where row.ContinentName == "europe" select row;

foreach ( Country row in europeList ) Console.WriteLine( row.Name );

Console.WriteLine();
Output:
czech
germany
france

No comments:

Post a Comment