英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论