Search code examples
c#entity-framework-6linq-to-entities

trying to get a orderby working on complex query


I cannot figure out where/how to put a orderby in this query. I am needing the query ordered by the field branch (which is from Driver_Detail.assigned_area_name.

I have tried it multiple places and ways but it just gets ignored.

var stopsList = (from s in context.Mobile_Stops
                             join d in context.Driver_Detail on s.driver_number equals d.driver_number
                             where EntityFunctions.TruncateTime(s.requested_delivery_dateTime) == dateToUse.Date
                             group new { s, d } by new { s.driver_number } into g 
                             select new DriverDaySummary
                             {
                                 driver_Number = g.FirstOrDefault().d.driver_number,// d.driver_number,
                                 driver_Name = g.FirstOrDefault().d.first_name,
                                 branch = g.FirstOrDefault().d.assigned_area_name,
                                 Total_Stop_Count = g.ToList().Select(x => x.s).Count(),
                                 Delivered_Stops = g.ToList().Select(x => x.s).Where(x => x.status == 30).Count(),
                                 Exceptoined_Stops = g.ToList().Select(x => x.s).Where(x => x.status == 40).Count(),
                                 Open_Stops = (g.ToList().Select(x => x.s).Count() - (g.ToList().Select(x => x.s).Where(x => x.status == 30).Count() + g.ToList().Select(x => x.s).Where(x => x.status == 40).Count())),
                                 
                             }).Distinct().ToList();

Solution

  • Just order by branch as ordering by assigned_area_name is not possible here as you are grouping by driver_number and take first assigned_area_name you can add OrderBy right after Distinct.

    The answer was provided by Selvin in the comments.