Azh*_*har 5 linq linq-to-entities linq-to-sql
如何通过Column变量进行排序,因为我在页面上有一个下拉列表,我想根据在此下拉列表中选择的sord顺序显示网格,例如价格,代码,评级,描述等等,我不想为每个单独写一个查询柱.
from lm in lDc.tbl_Products
where lm.TypeRef == pTypeId
orderby lm.Code ascending
select new;
Run Code Online (Sandbox Code Playgroud)
假设您想通过SQL进行排序,那么您需要传递排序列/类型.查询将被推迟,直到您实际执行select,因此您可以逐步构建查询,一旦完成,就执行它:
// Do you query first. This will NOT execute in SQL yet.
var query = lDC.tbl_Products.Where(p => p.TypeRef == pTypeId);
// Now add on the sort that you require... you could do ascending, descending,
// different cols etc..
switch (sortColumn)
{
case "Price":
query = query.OrderBy(q => q.Price);
break;
case "Code":
query = query.OrderBy(q => q.Code);
break;
// etc...
}
// Now execute the query to get a result
var result = query.ToList();
Run Code Online (Sandbox Code Playgroud)
如果您想在SQL之外执行此操作,那么只需获得没有排序的基本结果,然后根据您需要的排序条件将OrderBy应用于结果库.