为了支持仅接受特定数量的项目(5项)的API,我想将LINQ结果转换为总是包含该设定数量项目的较小项目组.
假设清单 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}
我想得到三个较小的列表,每个最多包含5个项目
{1, 2, 3, 4, 5}
{6, 7, 8, 9, 10}
{11, 12, 13, 14, 15}
{16, 17, 18}
我怎么能用LINQ做到这一点?我假设它涉及Group或者Aggregate,但我无法弄清楚如何写它.
Mar*_*ers 17
尝试这样的事情:
var result = items.Select((value, index) => new { Index = index, Value = value})
.GroupBy(x => x.Index / 5)
.Select(g => g.Select(x => x.Value).ToList())
.ToList();
Run Code Online (Sandbox Code Playgroud)
它的工作原理是根据原始列表中的索引将项目分组.
Dan*_*Tao 14
我会做这样的事情:
public static IEnumerable<IEnumerable<T>> TakeChunks<T>(this IEnumerable<T> source, int size)
{
// Typically you'd put argument validation in the method call and then
// implement it using a private method... I'll leave that to your
// imagination.
var list = new List<T>(size);
foreach (T item in source)
{
list.Add(item);
if (list.Count == size)
{
List<T> chunk = list;
list = new List<T>(size);
yield return chunk;
}
}
if (list.Count > 0)
{
yield return list;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
var list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
foreach (var chunk in list.TakeChunks(3))
{
Console.WriteLine(string.Join(", ", chunk));
}
Run Code Online (Sandbox Code Playgroud)
输出:
1, 2, 3 4, 5, 6 7, 8, 9 10
理由:
与其他方法相比,如多次调用Skip和/ Take或大花哨的LINQ查询,以上是:
| 归档时间: |
|
| 查看次数: |
7496 次 |
| 最近记录: |