本文介绍了LINQ - 动态排序依据条款无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有code是这样的:

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

它工作正常,只是排序依据。生成的SQL code不包含排序依据子句和记录进行排序。

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.

推荐答案

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

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

这篇关于LINQ - 动态排序依据条款无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 09:16