LINQ - dynamic orderby clause not working

I have a code like this:

//build query
var shops = (from p in dataContext.shops
let distance = dataContext.GetDistance(p.lat, p.lon, nearlat,nearlon)
                     join c in dataContext.shops_category on p.id equals c.poi_id
                     select new ShopsModel { p = p, distance = distance }
                         );
        }
//add dynamic orderby
if(somthig) 
  shops.OrderBy(distance)
else 
  shops.OrderBy(p.name)


//get records.
return shop.Take(30).ToList()

It works great except OrderBy. The generated SQL code does not contain the orderby clause, and the records are not sorted.

Any idea? Thanks for the help.

+5
source share
2 answers

OrderBy does not mutate the underlying data - it returns an enumerable with the appropriate ordering. You must return the result to the stores:

if (someCondition) 
{
  shops = shops.OrderBy(shop => shop.distance);
}
else 
{
  shops = shops.OrderBy(shop => shop.p.name);
}
+5
source

try the following:

Shops=shops.OrderBy(distance);
+1
source

All Articles