查詢排序 - OrderBy() ThenBy() OrderByDescending() ThenByDescending()
string[] names= { "mark", "steve", "adam" };
上升:
查詢語法
var sortedNames =
from name in names
orderby name
select name;
方法語法
var sortedNames = names.OrderBy(name => name);
sortedNames 按以下順序包含名稱:adam
,mark
,steve
降:
查詢語法
var sortedNames =
from name in names
orderby name descending
select name;
方法語法
var sortedNames = names.OrderByDescending(name => name);
sortedNames 按以下順序包含名稱:steve
,mark
,adam
按幾個領域排序
Person[] people =
{
new Person { FirstName = "Steve", LastName = "Collins", Age = 30},
new Person { FirstName = "Phil" , LastName = "Collins", Age = 28},
new Person { FirstName = "Adam" , LastName = "Ackerman", Age = 29},
new Person { FirstName = "Adam" , LastName = "Ackerman", Age = 15}
};
查詢語法
var sortedPeople = from person in people
orderby person.LastName, person.FirstName, person.Age descending
select person;
方法語法
sortedPeople = people.OrderBy(person => person.LastName)
.ThenBy(person => person.FirstName)
.ThenByDescending(person => person.Age);
結果
1. Adam Ackerman 29
2. Adam Ackerman 15
3. Phil Collins 28
4. Steve Collins 30