Search code examples
c#foreach.net-coreboost-foreach

Cleanest way to skip record in foreach based on condition


I have a nested foreach loop, and I would like to know which is the best way to skip a record based on an if condition in c#.

Below is my solution, if there are any improvements or suggestions please do let me know.

foreach (var ospMap in sourceSpecificMaps)
{
    foreach (var idMapSensorId in ospMap.SensorIds)
    {
        try
        {
            if (string.IsNullOrEmpty(idMapSensorId.SourceId))
            {
                throw new Exception($"SourceId couldn't be found in the { idMapSensorId.SensorId } sensor. The sensor is being skiped.");
            }
            _ospIdMapDictionary[GenCacheId(sourceId, idMapSensorId.SensorId)] = ospMap;
       }
       catch (Exception)
       {
            // We continue through the loop
            continue;
       }  
    }
}

Solution

  • Using exceptions like this is both slow (exceptions are very slow) and terrible practice. Just use the continue if you want to skip.

    foreach (var ospMap in sourceSpecificMaps)
    {
      foreach (var idMapSensorId in ospMap.SensorIds)
      {
        if (string.IsNullOrEmpty(idMapSensorId.SourceId))
        {
          continue; // TODO: Log the follwoing ?  SourceId couldn't be found in the { idMapSensorId.SensorId } sensor. The sensor is being skiped
        }
        _ospIdMapDictionary[GenCacheId(sourceId, idMapSensorId.SensorId)] = ospMap;
      }
    
    }