Device-to-Device (D2D) communications, regarded as a crucial technology for the Beyond Fifth-Generation (B5G) wireless networks, provide substantial benefits including elevated spectrum effectiveness, improved coverage, and traffic offloading. The mode selection and channel allocation play an Important role in ensuring the Quality of Service (QoS) and enhancing user experience in D2D communications. The dynamic switching of communication modes by D2D User Equipments (UEs) depends on the extent of shared resources among D2D pairs. In this paper, we examine the issue of joint mode selection and resource allocation for D2D communication within a cellular network in an uplink scenario. The main objective of this study is to optimize the overall sum rates of the network, while simultaneously guaranteeing the QoS requirements. Three communication modes are considered which are Direct Mode (MD), Relay-assisted Mode (RM), and Local route Mode (LM). In addition, each D2D pair has the option to be allocated either a dedicated channel or a reused channel. We present an innovative approach for the simultaneous determination of mode selection and channel allocation in D2D communication. The proposed approach is based on greedy strategy and a modified many-to-many matching technique that effectively selects the best communication mode and assigns the optimal channel for each D2D pair, respectively. The simulation results illustrate that the presented approach exhibits a significant improvement in the network performance when compared to the benchmark algorithms.