简化linq语句 (Sonar2971)

huangapple go评论72阅读模式
英文:

Simplify linq statment (Sonar2971)

问题

SonarCloud正在显示:S2971 - "IEnumerable" LINQ应简化

如何修复这个问题?

英文:

I have this Linq:

MyCars refCar = m_service.Cars?.ToList().FirstOrDefault(x => x.Id == car.refId);
...
return m_otherService.GetCar(refCar.RefCardId);

SonarCloud is showing: S2971 - "IEnumerable" LINQs should be simplified

How to fix that?

答案1

得分: 1

var refCar = m_service.Cars?.FirstOrDefault(x => x.Id == car.refId);
...
return m_otherService.GetCar(refCar?.RefCardId);

如果GetCar方法处理null值。否则,传递一个新的空对象。

英文:
var refCar = m_service.Cars?.FirstOrDefault(x => x.Id == car.refId);
...
return m_otherService.GetCar(refCar?.RefCardId);

If the GetCar method handles null values. Otherwise, pass a new empty object.

答案2

得分: 0

我猜SonarCloud希望你省略ToList()调用。这个调用创建了一个包含IEnumerable中所有项目的列表,但你只对一个项目感兴趣。你的做法会循环遍历整个IEnumerable。如果去掉ToList(),你只会循环直到找到满足条件的项目。因此,你的代码变成了

yCars refCar = m_service.Cars?.FirstOrDefault(x => x.Id == car.refId);
英文:

I guess SonarCloud wants you to omit the ToList() call. This call creates a list of all items in the IEnumerable, but you are only interested in one item. The way you do it, you will loop over the complete IEnumerable. If you drop ToList(), you will only loop until the item matching the condition is found. Hence your code becomes

yCars refCar = m_service.Cars?.FirstOrDefault(x => x.Id == car.refId);

huangapple
  • 本文由 发表于 2023年7月17日 20:44:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76704581.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定