I have a rent a car project. This is the table where I keep the rented vehicles I want to find the most rented vehicle in this table. How can I do this? So I want to find the most mentioned car Id in the table [I have to do it with context architecture. How can I do this with c # linq?]2
Advertisement
Answer
I want to find the most rented vehicle in this table.
So basically you want to find out how many times car 5 is rented, and how many times car 6 is rented, etc, and keep the carId with the highest rental count.
As you are working with a database, my advice would be to use GroupBy to make groups of rentals that have the same CarId, and then keep the group that has the most number of rentals = order by descending count and take the first.
We’ll use the overload of Queryable.GroupBy that has a parameter resultSelector, so we can select the number of rentals in the group as result.
// make groups of CarRentals that have the same CarId: var mostRentedCarId = dbContext.CarRentals.GroupBy(carRental => carRental.CarId, // parameter resultSelector: for every CarId and all CarRentals that have this CarId, // make one new object (carId, carRentalsWithThisCarId) => new { CarId = carId, RentalCount = carRentalsWithThisCarId.Count(), }) // order the groupBy result by descending rentalCount and take the first or default: .OrderByDescending(groupByResult => groupByResult.RentalCount) .FirstOrDefault();