2012-02-23 63 views
5

我有这样的代码:LINQ - 动态排序依据条款不起作用

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

它工作得很好,除了排序依据。生成的SQL代码不包含orderby子句,并且记录没有排序。

任何想法?感谢帮助。

回答

5

排序依据没有发生变异的基础数据 - 它返回一个枚举用适当的排序。您需要将结果返回商店:

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

试试这个:

Shops=shops.OrderBy(distance);