Summing the cost of order - CSharp LINQ

CSharp examples for LINQ:Aggregate

Description

Summing the cost of order

Demo Code



using System;//from   ww w.jav a  2s.c o m
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        var products = new List<Product> {
        new Product { Name = "MongoDB", OnHand = 0, UnitCost = 4.53M },
        new Product { Name = "Java", OnHand = 56, UnitCost = 12.50M },
        new Product { Name = "XML", OnHand = 300, UnitCost = 1.15M },
        new Product { Name = "MySQL", OnHand = 0, UnitCost = 2.00M },
        new Product { Name = "Whatsit", OnHand = 1, UnitCost = 1000.0M },
        new Product { Name = "MongoDB", OnHand = 0, UnitCost = 4.53M },
        new Product { Name = "MongoDB", OnHand = 0, UnitCost = 4.53M },
        new Product { Name = "MongoDB", OnHand = 0, UnitCost = 4.53M },
        new Product { Name = "MongoDB", OnHand = 0, UnitCost = 4.53M },
        new Product { Name = "MongoDB", OnHand = 0, UnitCost = 4.53M },
        new Product { Name = "Java", OnHand = 56, UnitCost = 12.50M },
        new Product { Name = "Java", OnHand = 56, UnitCost = 12.50M },
        new Product { Name = "XML", OnHand = 300, UnitCost = 1.15M }
      };

        Console.WriteLine("\nExample 16. Summing the cost of order O:");
        Order o = new Order(products);
        var productCosts = from p in o.Products
                           select p.UnitCost;

        var total = productCosts.Sum();
        Console.WriteLine("\tOrder o has a total summed cost of {0}", total);

        decimal checkTotal = 0.0M;
        foreach (Product p in products)
        {
            checkTotal += p.UnitCost;
        }
        Console.WriteLine("Totals match, so the query was correct ({0})", total == checkTotal);

    }
}
class Product
{
    public string Name;
    public int OnHand;
    public decimal UnitCost;
}
class Order
{
    public List<Product> Products;
    internal Order(List<Product> products)
    {
        Products = products;
    }
}

Result


Related Tutorials