gpt4 book ai didi

c# - 生成结构以填充树的查询或算法(C#、LINQ)

转载 作者:行者123 更新时间:2023-12-02 22:19:54 25 4
gpt4 key购买 nike

我找不到或想出一个通用且优雅的算法来填充树状结构。最简单的例子是博客存档:我有一堆记录,可以按日期选择和排序。我想要一棵树,其中年份可能是最高级别,月份是下一级,实际帖子标题是下一个。

到目前为止,我想出了一个简单直接的可行实现,但我确信可以使用 LINQ 等改进它。在这里,我只是按日期对记录进行排序,并反复检查年份或月份是否已更改,并相应地添加树节点。“BlogEntry”是一个同时引用父项和子项的类,稍后用于生成 HTML。

我欢迎提出改进算法的建议!

IEnumerable<Post> posts = db.Posts.OrderBy(p => p.DateCreated);
var topPost = posts.First();

int curYear = topPost.DateCreated.Year;
int curMonth = topPost.DateCreated.Month;

//create first "year-level" item
var topYear = new BlogEntry { Name = topPost.DateCreated.Year.ToString().ToLink(string.Empty) };
entries.Add(topYear);
var currentYear = topYear;

var topMonth = new BlogEntry { Name = topPost.DateCreated.ToString("MMMM").ToLink(string.Empty), Parent = currentYear };
currentYear.Children.Add(topMonth);
var currentMonth = topMonth;

foreach (var post in posts)
{
if(post.DateCreated.Year == curYear)
{
if (post.DateCreated.Month != curMonth)
{
//create "month-level" item
var month = new BlogEntry { Name = post.DateCreated.ToString("MMMM").ToLink(string.Empty), Parent = currentYear };
currentYear.Children.Add(month);
currentMonth = month;

curMonth = post.DateCreated.Month;
}

//create "blog entry level" item
var blogEntry = new BlogEntry { Name = post.Title.ToLink("/Post/" + post.PostID + "/" + post.Title.ToSeoUrl() ), Parent = currentMonth };
currentMonth.Children.Add(blogEntry);
}
else
{
//create "year-level" item
var year = new BlogEntry { Name = post.DateCreated.Year.ToString().ToLink(string.Empty) };
entries.Add(year);
currentYear = year;

curMonth = post.DateCreated.Month;
curYear = post.DateCreated.Year;
}
}

最佳答案

我创建了一个测试示例,以检查逻辑的正确性。我认为这就是您所需要的。

public class BlogEntyTreeItem
{
public string Text { set; get; }
public string URL { set; get; }
public List<BlogEntyTreeItem> Children { set; get; }

public List<BlogEntyTreeItem> GetTree()
{
NWDataContext db = new NWDataContext();
var p = db.Posts.ToList();

var list = p.GroupBy(g => g.DateCreated.Year).Select(g => new BlogEntyTreeItem
{
Text = g.Key.ToString(),
Children = g.GroupBy(g1 => g1.DateCreated.ToString("MMMM")).Select(g1 => new BlogEntyTreeItem
{
Text = g1.Key,
Children = g1.Select(i => new BlogEntyTreeItem { Text = i.Name }).ToList()
}).ToList()
}).ToList();

return list;
}
}

关于c# - 生成结构以填充树的查询或算法(C#、LINQ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13885783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com