是否可以在内联对象声明中使用循环?

ElH*_*aix 0 c# asp.net

对象ListOfCommentList<Comment>属性在哪里,最好的方法是:

                        ListOfComment = new List<Comment>
                        {
                            foreach(object a in b)
                            {
                                new Comment
                                {
                                    Type = "",
                                    Description = ""
                                }
                            }
                        }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 8

不是直接的,但你可以这样做:

ListOfComment = b.Select(a => new Comment {
    Type = "",
    Description = ""
}).ToList();
Run Code Online (Sandbox Code Playgroud)

要么:

ListOfComment = (from a in b
                 select new Comment {
                     Type = "",
                     Description = ""
                 }).ToList();
Run Code Online (Sandbox Code Playgroud)

要么:

ListOfComment = new List<Comment>(b.Select(a => new Comment {
    Type = "",
    Description = ""
}));
Run Code Online (Sandbox Code Playgroud)

要么:

ListOfComment = new List<Comment>(
    from a in b
    select new Comment {
        Type = "",
        Description = ""
    });
Run Code Online (Sandbox Code Playgroud)