LINQ - 动态orderby子句不起作用

时间:2012-02-23 09:04:35

标签: .net linq dynamic-queries

我有这样的代码:

//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()

除OrderBy外,它的工作正常。生成的SQL代码不包含orderby子句,并且记录未排序。

任何想法?谢谢你的帮助。

2 个答案:

答案 0 :(得分:5)

OrderBy不会改变底层数据 - 它返回一个具有适当排序的枚举。您需要将结果分配回商店:

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

答案 1 :(得分:1)

试试这个:

Shops=shops.OrderBy(distance);