使用嵌套的foreach循环降低代码的时间复杂度

时间:2020-09-26 14:25:00

标签: c#

我是C#开发的新手,我有一个如下的“ Comments”类。

$request->hasFile('document')

我们在主要评论中有子评论字段。我将每个注释对象另存为NoSQL DB中的文档。我需要获取所有这些注释,并将其所有子注释放入“ childComments”字段中,并将其转换为单个注释对象。如果注释处于级别0(最高级别或第一级别的注释),则ParentId将为null。 我写了下面的代码来检索它。

class Comments
{
    public Id {get; set;}
    public Text {get;set;}
    public ParentId {get;set;}
    public List<Comments> childComments {get;set;}
}
List<Comments> parentcomments = <from DB>.Where(t => t.ParentId == ObjectId.Empty).ToList();
List<Comments> childcomments = <from DB>.Where(t => t.ParentId != ObjectId.Empty).ToList();

foreach(comment t in parentcomments)
{
    finalCommentTree = AggregateComment(childcomments, t.Id);
}

代码运行良好,没有任何问题,但是问题在于时间复杂度。有没有办法降低时间复杂度并提高性能?

1 个答案:

答案 0 :(得分:0)

另一种方法:

List<Comments> parentList = new List<Comments>()
{   new Comments() { Id = 1, Text = "Parent1", ParentId = -1 },
    new Comments() { Id = 2, Text = "Parent2", ParentId = -1 },
    new Comments() { Id = 3, Text = "Parent3", ParentId = -1 },
};

List<Comments> childList = new List<Comments>()
{
    new Comments() { Id = 91, Text = "child1", ParentId = 3 },
    new Comments() { Id = 92, Text = "child2", ParentId = 2 },
    new Comments() { Id = 93, Text = "child3", ParentId = 1 },
    new Comments() { Id = 94, Text = "child4", ParentId = 2 },
    new Comments() { Id = 95, Text = "child5", ParentId = 2 },
    new Comments() { Id = 96, Text = "child6", ParentId = 1 },
    new Comments() { Id = 97, Text = "child7", ParentId = 2 }
};
            
List<Comments> k = ( from c in childList
                        join p in parentList
                        on c.ParentId equals p.Id
                        group c by new
                        {
                            c.ParentId
                            ,p.Text
                        } into stdGrp
                        select new Comments
                        {
                            Id = stdGrp.Key.ParentId,
                            Text = stdGrp.Key.Text,
                            ParentId = -1,
                            childComments = stdGrp.OrderBy(j => j.Id).ToList(),
                        }
                        ).ToList();