Tuesday, January 16, 2024

c# - How to use LINQ aggregate() function

This calling performs SUM on Population (with starting value = 0.)
    
public List<Country> Countries = new();
...
this.Countries.Add( new Country( "Czech", Country.ContinentEnum.EUROPE, 10 ) );
this.Countries.Add( new Country( "Poland", Country.ContinentEnum.EUROPE, 40 ) );
this.Countries.Add( new Country( "China", Country.ContinentEnum.ASIA, 1100 ) );
this.Countries.Add( new Country( "USA", Country.ContinentEnum.AMERICA, 340 ) );
...
int total = this.Countries.Aggregate( 0, (total,b) => total + b.Population );

MessageBox.Show( total.ToString() );  // -> 1490