sorting castsTo in order to preserve their order