Magento 2 – Get Region ID Given Region Code and Country ID

country-regionsfactorymagento-2.1magento2

I need to get the region_id given the region_code and the country_id, but I cannot manage to achieve it.
I've tried using the countryFactory and the regionFactory, but i do not understand what i'm doing wrong.

I have something like this

in the constructor the RegionFactory

public function __construct(
    \Magento\Directory\Model\RegionFactory $regionFactory
) {
    $this->_regionFactory = $regionFactory;
}

function getRegionIdByCode($code){


 $region = $this->_regionFactory->create()
            ->loadByCode($code,$country_id)->getFirstItem();
...
}
//where code is correctly calculated based on a csv with all italian regions

Cannot manage to work with the $region object. I need to do something like
$region->getRegionId()

Is it possible??

Best Answer

This has to work

$region = $this->_regionFactory->create();
$regionId = $region->loadByCode($code, $country_id)->getId();