LINQ - dynamic orderby clause does not work

守給你的承諾、 提交于 2019-12-10 14:16:55

问题


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.


回答1:


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);
}



回答2:


try this:

Shops=shops.OrderBy(distance);


来源:https://stackoverflow.com/questions/9409878/linq-dynamic-orderby-clause-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!