private static Order CreateOrder() { Product p1 = new Product { ID = 1, Description = "p1", Price = 9 }; Product p2 = new Product { ID = 2, Description = "p2", Price = 6 }; Order order = new VIPOrder { ID = 4, Description = "Order for John Doe.", OrderLines = new List<OrderLine>() { new OrderLine { ID = 5, Amount = 1, Product = p1}, new OrderLine { ID = 6, Amount = 10, Product = p2}, } }; return order; }
static void Main(string[] args) { Product product1 = new Product { Description = "Test" }; var orders = new List<Order>() { new Order { OrderLines = new List<OrderLine>() { new OrderLine() { Amount = 22, Product = product1 }, new OrderLine() { Amount = 11, Product = new Product { Description = "Test" }}, } }, new Order() { OrderLines = new List<OrderLine>() }, new Order { OrderLines = new List<OrderLine>() { new OrderLine() { Amount = 22, Product = product1 }, new OrderLine() { Amount = 33, Product = new Product { Description = "Test" }}, } }, }; // Grouping and projection to anonymous type var result = from o in orders from l in o.OrderLines group l by l.Product into p select new { Product = p.Key, Amount = p.Sum(x => x.Amount) }; Console.WriteLine("Group and projection: {0}", string.Join(", ",result.Select(x => x.Amount))); // Projection to existing type var result2 = from o in orders from l in o.OrderLines select new ProductAmount { Amount = l.Amount, Description = l.Product.Description }; Console.WriteLine("Projection: {0}", string.Join(", ", result2.Select(x => x.Amount))); Console.ReadLine(); }