如果您希望将列表分成 12 个元素的块,您可以使用 C# 10 中新增的 Chunk Linq 扩展。如果您不使用 C# 10,库 MoreLinq 中提供了等效的扩展,它有一个不同的名称:Batch。
// Creating a sample list of dummy elements
// There will be 100 strings from "0" to "99".
var MyList = Enumerable.Range(0, 100)
.Select(i => $"{i}");
// Creating a list of chunks containing 12 elements
var ChunkedElements = MyList
.Chunk(12);
// Using the chunked list.
foreach (var chunk in ChunkedElements)
{
// Do what you want with the 12 elements
Console.WriteLine("New Chunk");
foreach(var e in chunk)
{
Console.WriteLine(e);
}
}
输出:
New Chunk
0
1
2
3
4
5
6
7
8
9
10
11
New Chunk
12
13
14
15
16
17
18
19
20
21
22
23
New Chunk
24
25
26
27
28
29
30
31
32
33
34
35
New Chunk
36
37
38
39
40
41
42
43
44
45
46
47
New Chunk
48
49
50
51
52
53
54
55
56
57
58
59
New Chunk
60
61
62
63
64
65
66
67
68
69
70
71
New Chunk
72
73
74
75
76
77
78
79
80
81
82
83
New Chunk
84
85
86
87
88
89
90
91
92
93
94
95
New Chunk
96
97
98
99
如果您只想要每 12 个元素,这里是经典 for 循环的 Linq 替代方案。它没有好坏之分,但根据具体情况可能会有用。
// Creating a sample list of dummy elements
// There will be 100 strings from "0" to "99".
var MyList = Enumerable.Range(0, 100)
.Select(i => $"{i}");
// Filtering the list to get only the 12th elements
var FilteredElements = MyList
.Where((e, i) => i % 12 == 0);
// Using the filtered list
foreach (var e in FilteredElements)
{
// Here do what you want with each element.
Console.WriteLine(e);
}
输出:
0
12
24
36
48
60
72
84
96
解释:
.Where((e, i) => i % 12 == 0) 是工作完成的地方。 linq 扩展方法Where 有一个以 Func 为参数的重载。见the doc。第二个参数是集合元素的索引。
所以.Where((e, i) => i % 12 == 0) 只保留集合中索引i 可被12 整除的元素(i % 12 == 0)。因此结果只包含 12 的倍数。