fork(4) download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace TestApp
  6. {
  7.  
  8. class Program
  9. {
  10. public class Order
  11. {
  12. public Order()
  13. {
  14. Items = new List<OrderItem>();
  15. }
  16.  
  17. public string Code { get; set; }
  18. public ICollection<OrderItem> Items { get; set; }
  19. }
  20.  
  21. public class OrderItem
  22. {
  23. public OrderItem()
  24. {
  25. SubItems = new List<SubItem>();
  26. }
  27.  
  28. public decimal Quantity { get; set; }
  29. public decimal Price { get; set; }
  30. public ICollection<SubItem> SubItems { get; set; }
  31. }
  32.  
  33. public class SubItem
  34. {
  35. public DateTime Date { get; set; }
  36. public decimal Quantity { get; set; }
  37. public string UserName { get; set; }
  38. }
  39.  
  40. static void Main(string[] args)
  41. {
  42. Order order = new Order();
  43. order.Code = "123";
  44. order.Items.Add(new OrderItem()
  45. {
  46. Price = 30,
  47. Quantity = 3,
  48. SubItems = new List<SubItem>()
  49. {
  50. new SubItem() { Date = DateTime.Now, Quantity = 1, UserName = "User1" },
  51. new SubItem() { Date = DateTime.Now, Quantity = 2, UserName = "User2" }
  52. }
  53. });
  54.  
  55.  
  56. order.Items.Add(new OrderItem()
  57. {
  58. Price = 500,
  59. Quantity = 50,
  60. SubItems = new List<SubItem>()
  61. {
  62. new SubItem() { Date = DateTime.Now, Quantity = 20, UserName = "User1" },
  63. new SubItem() { Date = DateTime.Now, Quantity = 20, UserName = "User2" },
  64. new SubItem() { Date = DateTime.Now, Quantity = 10, UserName = "User3" }
  65. }
  66. });
  67.  
  68.  
  69. order.Items.Add(new OrderItem()
  70. {
  71. Price = 1000,
  72. Quantity = 50,
  73. SubItems = new List<SubItem>()
  74. });
  75.  
  76.  
  77. var res = order.Items
  78. .SelectMany(i => i.SubItems.DefaultIfEmpty(), (Item, Sub) => new { Item, Sub })
  79. .Select(r => new { order.Code, r.Item.Price, ItemQuantity = r.Item.Quantity, SubItemQuantity = r.Sub == null ? null : (Decimal?) r.Sub.Quantity ,UserName = r.Sub == null ? (string)null : r.Sub.UserName });
  80.  
  81. foreach(var x in res)
  82. {
  83. System.Console.WriteLine(x.ToString());
  84. }
  85. }
  86. }
  87. }
Success #stdin #stdout 0.05s 34024KB
stdin
Standard input is empty
stdout
{ Code = 123, Price = 30, ItemQuantity = 3, SubItemQuantity = 1, UserName = User1 }
{ Code = 123, Price = 30, ItemQuantity = 3, SubItemQuantity = 2, UserName = User2 }
{ Code = 123, Price = 500, ItemQuantity = 50, SubItemQuantity = 20, UserName = User1 }
{ Code = 123, Price = 500, ItemQuantity = 50, SubItemQuantity = 20, UserName = User2 }
{ Code = 123, Price = 500, ItemQuantity = 50, SubItemQuantity = 10, UserName = User3 }
{ Code = 123, Price = 1000, ItemQuantity = 50, SubItemQuantity = , UserName =  }