c# - Sonar 问题 - 删除对局部变量的无用赋值

标签 c# sonarqube sonarqube-scan

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

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

remove this useless assignment to local variable c#

最佳答案

这个怎么样:

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/

相关文章:

c# - DllImport 如何识别最新的 .dll 版本?

active-directory - 带有 LDAP 1.4 配置的 Sonar 4.1.1

java - 我想知道使用 Sonar 的最佳方法是什么?

sonarqube - 如何在 Google Cloud Build 步骤中包含 sonarqube 扫描步骤

c# - 从 ConcurrentDictionary 继承时出现编译器错误

c# - 如何更改 WPF 复选框勾号的颜色?

c# - 如何使用 Monotouch for iPad 创建圆形按钮?

java - Sonar 误报问题

java - 导入语句上的 SonarQube 规则 "common-java:DuplicatedBlocks"

java - Sonar 扫描仪分析在 util.lang.ConcreteReceiverGuard 上挂起