声纳问题 - 删除对局部变量的无用赋值

Sonar issue - Remove this useless assignment to local variable

我正在使用下面提到的一段代码:

IList<Comment> listComments = new List<Comment>();
foreach (var comment in paxComments.Where(x => x.Id== paxID))
{
    listComments.Add(new Comment()
    {
        CommentID = comment.CommentId,
        Text = comment.Comment,
    });
}

这里声纳说 "Remove this useless assignment to local variable"。如何在不使用 new 关键字初始化的情况下添加到列表?

Sonar 评论是 "Remove this useless assignment to local variable "listComments"。"

我浏览了以下链接,但没有得到答案。

Sonar complaining about useless assignment of local variable

这个怎么样:

IList<Comment> listComments = paxComments.Where(x => x.Id== paxID).ToList();

如果它们是同一类型。否则在 where:

之后投射必填字段
IList<Comment> listComments = paxComments.Where(x => x.Id== paxID).Select(x=> new Comment({CommentId = x.commentId, Text = x.Text})).ToList();

我想 ForEach 循环是不必要的。