想要一个查询在 Linq 查询中按变量排序 [英] want a Query to make order by variable in Linq query

查看:17
本文介绍了想要一个查询在 Linq 查询中按变量排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何按列变量排序,因为我在页面上有一个下拉列表,我想根据此下拉列表中选择的排序显示网格,例如价格、代码、评级、描述等,我不想单独编写查询每一列.

How to make order by Column variable because I have a dropdown on page and I want to show grid according to sord order selected in this Dropdown e.g Price, Code, rating, description etc etc. and I donot want to write a separate query for each column.

from lm in lDc.tbl_Products
where lm.TypeRef == pTypeId
 orderby lm.Code ascending
 select new; 

推荐答案

假设您想通过 SQL 进行排序,那么您需要传入排序列/类型.查询会推迟到您实际执行选择之后,以便您可以分步构建查询,完成后像这样执行:

Assuming you want to do the sorting via SQL then you will need to pass in the sort column/type. The query is deferred until you actually do the select so you can build up the query in steps and once you are done execute it like so:

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

如果您想在 SQL 之外执行此操作,则只需获得不进行排序的基本结果,然后根据您需要的排序条件将 OrderBy 应用于结果.

If you want to do it outside of SQL then just get a basic result with no sorting and then apply an OrderBy to the result base on the sort criteria you need.

这篇关于想要一个查询在 Linq 查询中按变量排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆