C# Flatten data by Linq

When I work on the project, I usually run into a problem about flatting data.
Because the original data could in the nested property, I have to get it out.
The following is an example about nested properties, and the requirement is that I must get all OrderDetailNumber.

Finally, I found an easy method that is use SelectMany.

LINQ SelectMany

Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.Linq;
using System.Collections.Generic;

namespace FlattenResult
{
internal class Program
{
public class Order
{
public string OrderNumber { get; set; }

public List<OrderDetail> orderDetails { get; set; }

public class OrderDetail
{
public string OrderDetailNumber { get; set; }
}
}

static void Main(string[] args)
{
var orders = new List<Order>
{
new Order
{
OrderNumber = "202305121111",
orderDetails = new List<Order.OrderDetail>
{
new Order.OrderDetail
{
OrderDetailNumber = "OD0001",
},
new Order.OrderDetail
{
OrderDetailNumber = "OD0001",
}
}
},
new Order
{
OrderNumber = "202305121112",
orderDetails = new List<Order.OrderDetail>
{
new Order.OrderDetail
{
OrderDetailNumber = "OD0003",
},
new Order.OrderDetail
{
OrderDetailNumber = "OD0004",
}
}
}
};

var orderDetailNumbers = orders.SelectMany(s => s.orderDetails)
.Select(s => s.OrderDetailNumber)
.ToList();

orderDetailNumbers.ForEach(f =>
{
Console.WriteLine(f);
});
}
}
}

Output:

1
2
3
4
OD0001
OD0001
OD0003
OD0004