I have the following code for Customers and their orders. I want to list all the customerID and the corresponding count of orders. How do I achieve it using LINQ?
Note: I am new to LINQ and var.
protected void Page_Load(object sender, EventArgs e)
{
List<Order> orderListForCus1 = new List<Order>();
Order ord1 = new Order(1, new DateTime(2011, 9, 1));
Order ord2 = new Order(1, new DateTime(2011, 8, 1));
orderListForCus1.Add(ord1);
orderListForCus1.Add(ord2);
Customer cus1 = new Customer();
cus1.CustomerID = 1;
cus1.OrderList = orderListForCus1;
List<Customer> customerRecordsBook = new List<Customer>();
customerRecordsBook.Add(cus1);
var orderCounts = from c in customerRecordsBook
select new { c.CustomerID, OrderCount = c.OrderList.Count() };
}
You’re almost there.
You can loop over your anonymously-typed objects just like any other objects:
Note that
omust be declared asvar, since the type has no name that you can use.In your case, you don’t actually need LINQ; you can just use the
List<T>directly: