比如已知是 10001个章节,第个页面最多显示100个标签,则最终会有3层。以下代码是自己写出,由gpt将递归优化为while循环。
void Main() { int totalChapterCount = 10001; int maxChapterCount = 100; var chapters = new List<Chapter>(); for (var i = 0; i < totalChapterCount; i++) chapters.Add(new Chapter(i + 1, i + 1) { }); var result = groupChapters(chapters, maxChapterCount); result.Dump(); } public class Chapter { public int StartIndex { get; set; } public int EndIndex { get; set; } public List<Chapter> SubChapters { get; set; } public Chapter(int start, int end) { this.StartIndex = start; this.EndIndex = end; this.SubChapters = new List<Chapter>(); } } public List<Chapter> groupChapters(List<Chapter> chapters, int maxChapterCount) { while (chapters.Count > maxChapterCount) { var newChapters = new List<Chapter>(); for (int i = 0; i < chapters.Count; i += maxChapterCount) { var group = chapters.Skip(i).Take(maxChapterCount).ToList(); var start = group.First().StartIndex; var end = group.Last().EndIndex; var newChapter = new Chapter(start, end) { SubChapters = group }; newChapters.Add(newChapter); } chapters = newChapters; } return chapters; }
为了便于理解,备忘原始递归:
public List<Chapter> groupChapters(List<Chapter> chapters, int maxChapterCount) { var groups = chapters.Select((x, index) => new { Chapter = x, GroupIndex = index / maxChapterCount }) .GroupBy(item => item.GroupIndex) .Select(x => new Chapter(x.First().Chapter.StartIndex, x.Last().Chapter.EndIndex) { SubChapters = x.ToList().Select(y=>y.Chapter).ToList() }) .ToList(); if(groups.Count <= maxChapterCount) return groups; return groupChapters(groups,maxChapterCount); }
标签:Chapter,c#,标签,List,chapters,int,分组,var,maxChapterCount From: https://www.cnblogs.com/nanfei/p/17929499.html