Linq to SQL -如何对查询结果进行排序

643ylb08  于 2022-12-06  发布在  其他
关注(0)|答案(5)|浏览(162)

我有一个正在检索的LINQ查询,尽管在它的上下文中我将如何对输出进行排序,我尝试了sortby等方法,但没有效果

DataClasses1DataContext db = new DataClasses1DataContext();
    var returnall = from p in db.Orders
                    select p.ShipName;
qlvxas9a

qlvxas9a1#

var returnall = from p in db.Orders
                orderby p.ShipName
                select p.ShipName;

各种LINQ函数的方便参考可在MSDN samples page上找到。

ekqde3dh

ekqde3dh2#

您可以使用OrderBy对多个属性的单个属性进行排序,还可以使用ThenBy

DataClasses1DataContext db = new DataClasses1DataContext();
 var returnall = db.OrderBy(r=> r.OrderDelivaryDate).
                    ThenBy(r => r. OrderName);

此查询将首先按OrderDelivaryDate排序,然后按OrderName排序
下面是一些简单的linq查询http://msdn.microsoft.com/en-us/vcsharp/aa336756#thenBySimple

svujldwt

svujldwt3#

var ret = db.Orders.OrderBy( x => x.ShipName );
ccrfmcuu

ccrfmcuu5#

要对一个多个字段的查询结果进行排序,请执行以下操作:

数据:

List<Employee> emp = new List<Employee>() { new Employee() { emp_id = 101, emp_name = "David", emp_lang = "Java", dpt_id = 1 }
                                                    ,new Employee() { emp_id = 102, emp_name = "Lana",emp_lang = "C#", dpt_id = 2 }
                                                    ,new Employee() { emp_id = 103, emp_name = "Sona",emp_lang = "Java", dpt_id = 3 }
                                                    ,new Employee() { emp_id = 104, emp_name = "Mike",emp_lang = "C++", dpt_id = 3 }
                                                    ,new Employee() { emp_id = 105, emp_name = "Roma",emp_lang = "C#", dpt_id = 1 }

查询:

var res = from e in emp
              orderby e.emp_lang, e.dpt_id
              select new { e.emp_name, e.emp_lang, e.dpt_id }

结果

{ emp_name = "Roma", emp_lang = "C#", dpt_id = 1 }
{ emp_name = "Lana", emp_lang = "C#", dpt_id = 2 }
{ emp_name = "Mike", emp_lang = "C++", dpt_id = 3 }
{ emp_name = "David", emp_lang = "Java", dpt_id = 1 }
{ emp_name = "Sona", emp_lang = "Java", dpt_id = 3 }

相关问题