In The Hobbit, why is it necessary for Gandalf to leave the expedition?
I assume you are referring to Chapter 2 when the dwarves suddenly notice that Gandalf is no longer with them before they get captured by the trolls. Although at first we are told they are most put out by his unexpected absence - for he vanishes without saying that he is leaving - it all works out for the best, as Gandalf is able to return and to save them from the trolls who have captured them and are imminently about to eat roast dwarf for dinner. When Gandalf has tricked the trolls into staying out in sunlight, he explains why he left them:
"I went on to spy out our road. It will soon become dangerous and difficult. Also I was anxious about replenishing our small stoc of provisions. I had not gone very far, however, when I met a couple of friends of mine from Rivendell."
It is these elvish friends from Rivendell that inform Gandalf about the two trolls, and he fears that the expedition might have become "waylaid" by the trolls, so he hurries back to save them.