orderby
order by子句指定元素的排序字段和排序方式。当有多个排序字段时,由字段顺序确定主次关系,可指定升序和降序两种排序方式,比如按时间排序等等。默认是升序,加上descending表示降序。示例代码为:
var str = from p in PersonList orderby p.age select p;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace linq
{
class student //定义数据源
{
public string name { get; set; }
public int age { get; set; }
public int sex { get; set; }
}
class Program
{
static void Main(string[] args)
{
var items = new List<student>(); // 要查询的数据源
items.AddRange(new student[]
{ new student{name="Tom",age=20,sex=1},
new student{name="Jim",age=23,sex=1},
new student{name="John",age=24,sex=1},
new student{name="Marry",age=22,sex=0},
new student{name="Lucy",age=21,sex=0}
});
//按 age 字段进行排序 升序
var data = from a in items orderby a.age select a;
//lambda表达式形式用Orderby()方法
// var data=items.Orderby(val=>val.age/1);
//降序代码
//lambda表达式形式用OrderByDescending(val=>val.age/1)方法
//var data=from a in items orderby a.age descending select a;
foreach (var ss in data)
{
//输出姓名与年龄
Console.WriteLine(ss.name+" "+ss.age.ToString());
}
}
}
}
orderby子句同样能够进行多个条件排序,只需要将这些条件用“,”号分割即可。