Search code examples
c#linqsonarqubeienumerable

Simplify linq statment (Sonar2971)


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?


Solution

  • 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.