Search code examples
c#linqmorelinq

OrderBy is not working


I am trying the following code:

public IList<Brand> GetMobileDeviceBrands()
{
     var dataContext = dataContextFactory.CreateContext();

     var brands = (from b in dataContext.Brands
                   join d in dataContext.Devices on b.ID equals d.BrandID
                   where d.DeviceTypeID != 1
                   select b).OrderBy(b => b.Name).Distinct().ToList();

     return brands;         // not ordered by Name here
}

But not getting the ordered result as expected.

If I write orderBy in the controller as:

var Brands = devicesListService.GetMobileDeviceBrands().OrderBy(b => b.Name).ToList();

Its doing well. I don't know what is going wrong.


Solution

  • The distinct operator does not guarantee to keep the order of the values intact, so you need to swap the orderby and distinct operators:

    var brands = (from b in dataContext.Brands
                       join d in dataContext.Devices on b.ID equals d.BrandID
                       where d.DeviceTypeID != 1
                       select b).Distinct().OrderBy(b => b.Name).ToList();