C# LINQ select group
void Main() { List<Order> orders = new List<Order> { new Order { OrderID = 1, OrderDate = DateTime.Parse("2023-09-21") }, new Order { OrderID = 2, OrderDate = DateTime.Parse("2023-09-22") }, // 添加更多订单 }; List<OrderDetail> orderDetails = new List<OrderDetail> { new OrderDetail { OrderDetailID = 1, OrderID = 1, ProductID = 101, UnitPrice = 10.0m, Quantity = 2 }, new OrderDetail { OrderDetailID = 2, OrderID = 1, ProductID = 102, UnitPrice = 15.0m, Quantity = 3 }, new OrderDetail { OrderDetailID = 3, OrderID = 2, ProductID = 103, UnitPrice = 20.0m, Quantity = 4 }, // 添加更多订单详情 }; var query = from order in orders join orderDetail in orderDetails on order.OrderID equals orderDetail.OrderID into orderGroup select new { Order = order, OrderDetails = orderGroup.ToList() }; foreach (var result in query) { Console.WriteLine($"Order ID: {result.Order.OrderID}, Order Date: {result.Order.OrderDate}"); Console.WriteLine("Order Details:"); foreach (var orderDetail in result.OrderDetails) { Console.WriteLine($" - ProductID: {orderDetail.ProductID}, Unit Price: {orderDetail.UnitPrice}, Quantity: {orderDetail.Quantity}"); } Console.WriteLine(); } } // Define other methods and classes here public class Order { public int OrderID { get; set; } public DateTime OrderDate { get; set; } // 其他订单相关的属性 } public class OrderDetail { public int OrderDetailID { get; set; } public int OrderID { get; set; } public int ProductID { get; set; } public decimal UnitPrice { get; set; } public int Quantity { get; set; } // 其他订单详情相关的属性 }
執行結果
Order ID: 1, Order Date: 2023/9/21 上午 12:00:00
Order Details:
- ProductID: 101, Unit Price: 10.0, Quantity: 2
- ProductID: 102, Unit Price: 15.0, Quantity: 3
Order ID: 2, Order Date: 2023/9/22 上午 12:00:00
Order Details:
- ProductID: 103, Unit Price: 20.0, Quantity: 4
留言
張貼留言