Manos
Manos

Reputation: 1501

Linq query to calculate sum of object properties

I have a list of Customers List<Customer> customers = new List<Customer>();with this format

class Customer {
    public string Name;
    public string City;
    public Order[] Orders;

}

class Order {
    public int Quantity;
    public Product Product;

}

class Product {
    public string Name;
    public decimal Price;
}

Every customer is instantiated like this:

    Customer customer3 = new Customer {
        Name = "Kostas",
        City = "Athens",
        Orders = new Order[] {
            new Order {Quantity = 1, Product = new Product {Name = "Juice", Price = 20 } },
        },
    };

I want to write a LINQ query that prints out the name of the customer and the total amount of all the orders.

So far after lots of tries the closest i have done is this, but it does not work as intended.

        var query= from c in customers
                        from p in c.Orders
                        let summary = p.Product.Price * p.Quantity
                        select new {c.Name, summary };

Upvotes: 0

Views: 2997

Answers (2)

shapekey
shapekey

Reputation: 11

you should be change your way to solve it.

I think you should be create a property for 'summary' on customer class

like this

  class Customer
{
    public string Name;
    public string City;
    public Order[] Orders;
    public int Summary
    {
        get
        {
            int result = 0;
            foreach(Order order in this.Orders)
            {
                result += order.Product * order.Quantity;
            }
            return result;
        }
    }
}

and then you can get just foreach code, simply

        foreach(Customer customer in customers)
        {
            Console.WriteLine("{0}/{1}", customer.Name, customer.Summary);
        }

Upvotes: 0

Dave Zych
Dave Zych

Reputation: 21887

Use Select to create a list of anonymous objects with the Sum of the order quantity and product price. Note that this is using expression syntax rather than query syntax.

var query = customers.Select(c => new {
    Name = c.Name,
    OrderTotal = c.Orders.Sum(o => o.Quantity * o.Product.Price)
});

This will result in an IEnumerable<T>, where T is an anonymous object containing props for the Name and OrderTotal.

Upvotes: 2

Related Questions