我正在使用下面提到的一段代码:
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,
});
}
Sonar 在这里说“删除对局部变量的无用分配”。如何在不使用新关键字初始化列表的情况下将其添加到列表中?
Sonar 评论是“删除对局部变量“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 循环是不必要的。
关于c# - Sonar 问题 - 删除对局部变量的无用赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50227581/