Wednesday, August 21, 2019

C# - How to get sum for field in LINQ with both syntax variants

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

double value;

/* -- sum - query syntax variant */

value = ( from row in listCountry                      
          select row.Population ).Sum();

Console.WriteLine( string.Format( "Sum of population(variant 1) = {0}", value ) );

/* -- sum - fluent syntax variant */

value = listCountry.Sum( x => x.Population );

Console.WriteLine( string.Format( "Sum of population (variant 2) = {0}", value ) );
Output:
Sum of population(variant 1) = 1680
Sum of population (variant 2) = 1680

No comments:

Post a Comment