首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# LINQ 實現每 N 條數據換行(分組輸出)

     編輯:程式設計綜合問答

需求

將查詢結果每 3 條作為一組,輸出為巢狀集合 IEnumerable>。

標準寫法:Select 索引 + GroupBy

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;
        }
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved