想要一个查询在 Linq 查询中按变量排序

编程入门 行业动态 更新时间:2024-10-11 15:13:58
本文介绍了想要一个查询在 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 查询中按变量排序

本文发布于:2023-10-26 18:15:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530951.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   Linq

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!