將查詢結果每 3 條作為一組,輸出為巢狀集合 IEnumerable。
var grouped = query
.Select((item, index) => new { item, index })
.GroupBy(x => x.index / 3) // 整除分組
.Select(g => g.Select(x => x.item)); // 投影回原類型
// 使用示例
foreach (var group in grouped) {
Console.WriteLine(string.Join(", ", group));
// 或生成 HTML 每組一行
}
擴展方法封裝(復用)
public static class LinqExtensions {
public static IEnumerable> Batch(this IEnumerable source, int size) {
if (size <= 0) throw new ArgumentOutOfRangeException(nameof(size));
return source
.Select((item, index) => new { item, index })
.GroupBy(x => x.index / size)
.Select(g => g.Select(x => x.item));
}
}
// 調用
var batches = query.Batch(3);
替代方案:MoreLINQ 库
// NuGet: MoreLINQ
using MoreLinq;
var batches = query.Batch(3); // 內部優化,避免匿名對象分配
性能對比
方法 分配 適用場景
Select+GroupBy 匿名對象、分組字典 中小數據集、無依賴
MoreLINQ Batch 迭代器塊、無額外對象 大數據流、高性能要求
手寫迭代器 最少 極致優化、教學
手寫高性能迭代器
public static IEnumerable> BatchFast(this IEnumerable source, int size) {
if (size <= 0) throw new ArgumentOutOfRangeException(nameof(size));
using (var e = source.GetEnumerator()) {
while (e.MoveNext()) {
var batch = new List(size) { e.Current };
while (batch.Count < size && e.MoveNext())
batch.Add(e.Current);
yield return batch;
}
}
}
C 語言新手:#include 缺少標頭檔名稱導致第一行報錯
Android ListView 項目不顯示:被 TextView 佔據空間
jQuery mouseover 與 mouseenter 核心區別:事件冒泡與子元素觸發機制詳解
Android SharedPreferences 數據持久化失效:正確的編輯提交流程與生命周期調用時機
Android LayoutInflater 切換 Activity 失敗:正確在 onCreate 中設置佈局
iOS 多數值求最大值最佳實踐:數組排序法與 Key-Value Coding 替代方案
Objective-C 陣列嵌套添加時數值重複:每次迴圈需建立新的 NSMutableArray 實例
Copyright © 程式碼之家 All Rights Reserved