Wednesday, August 21, 2019

C# - How to get sum for field in LINQ, where condition, 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
          where row.ContinentName == "europe" 
          select row.Population ).Sum();

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

/* -- sum - fluent syntax variant */

value = listCountry.Where( w => w.ContinentName == "europe" ).Sum( x => x.Population );

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

No comments:

Post a Comment