使用orderby leyword对列表进行升序或降序排序。
以下是列表-
List<string> myList = new List<string>();
myList.Add("truck");
myList.Add("bus");
myList.Add("bicycle");
myList.Add("motorbike");现在让我们以降序对列表进行排序-
myLen = from element in myList orderby element.Length descending select element;
这是完整的代码-
using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
static void Main() {
List<string> myList = new List<string>();
myList.Add("truck");
myList.Add("bus");
myList.Add("bicycle");
myList.Add("motorbike");
var myLen = from element in myList
orderby element.Length
select element;
Console.WriteLine("Ascending order...");
foreach (string str in myLen){
Console.WriteLine(str);
}
myLen = from element in myList
orderby element.Length descending
select element;
Console.WriteLine("Descending order...");
foreach (string str in myLen) {
Console.WriteLine(str);
}
}
}输出结果
Ascending order... bus truck bicycle motorbike Descending order... motorbike bicycle truck bus