C#中使用orderby根据特定顺序按指定字段对集合中的元素进行排序。顺序可以是升序或降序。
以下是我们的元素列表-
List<string> myList = new List<string>(); //添加元素 myList.Add("iOS by Apple"); myList.Add("Android by Google"); myList.Add("Symbian by Nokia");
现在,使用Orderby以降序对元素进行排序-
var 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("iOS by Apple"); myList.Add("Android by Google"); myList.Add("Symbian by Nokia"); var myLen = from element in myList orderby element.Length descending select element; Console.WriteLine("Descending order..."); foreach (string str in myLen) { Console.WriteLine(str); } } }
输出结果
Descending order... Android by Google Symbian by Nokia iOS by Apple