Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - dynamic orderby clause does not work

I have 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's works fine except OrderBy. Generated SQL code does not contains orderby clause and the records are not sorted.

Any Idea? Thanks for help.

like image 366
itdebeloper Avatar asked Feb 23 '12 09:02

itdebeloper


Video Answer


1 Answers

OrderBy does not mutate the underlying data - it returns an enumerable with the appropriate ordering. You need to assign the result back to shops:

if (someCondition) 
{
  shops = shops.OrderBy(shop => shop.distance);
}
else 
{
  shops = shops.OrderBy(shop => shop.p.name);
}
like image 122
Rich O'Kelly Avatar answered Oct 14 '22 21:10

Rich O'Kelly