0

I have a class Customer that holds an array of class Order.

    class Customer
{
    public string firstname { get; set; }
    public string lastname { get; set; }

    public Order[] orders {get; set;}
}

I need to write a LINQ to find the total number of orders of all customers but I don't understand how to do it. For example I have created 8 customers and they have 3 orders each so I should print out 24.

Any help is appreciated!

1
  • Can you please provide some code which you already did? Commented Feb 9, 2017 at 3:56

4 Answers 4

4

You could use either of these.

// flattens order collection.
var result = custList.SelectMany(x => x.orders).Count();

or

var result = custList.Sum(x=>x.orders.Count());
Sign up to request clarification or add additional context in comments.

1 Comment

Yes that did the trick! Thank you. I think I understand how to use LINQ on objects of object.
0
 var result = custList.SelectMany(x => x.orders).Count();

3 Comments

Thank you for your reply. So that returns for me 8 which is probably seeing an order for each customer but not counting the number of orders per customer....which should be returning 24 in my case
you should use selectMany in that case
Correct - the select is returning an Order[] for each customer, and then counting the number of those - which will be the same as the number of customers. You'll need to use Sum or SelectMany as proposed in the answer above.
0

You certainly can do it as var countOfOrders = customers.SelectMany(x => x.orders).Count();, but you many find it more readable as this:

var orders =
    from c in customers
    from o in c.orders
    select o;

var countOfOrders = orders.Count();

Comments

0

You have to use SelectMany(). This method will makes one list of all orders. Then you can do count:

var allordersNumber = customers.SelectMany(x => x.Orders).Count();

Please read more about SelectMany() in MSDN.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.