ใช้ LINQ orderby keyword เรียง List ใน C#
ตัวอย่าง: เรียงตามความยาว String
var myLen = from element in myList orderby element.Length 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("cab");
myList.Add("motorbike");
var myLen = from element in myList orderby element.Length select element;
foreach (string str in myLen)
{
Console.WriteLine(str);
}
}
}
Output
bus cab truck motorbike
เรียงจากสั้นไปยาว (Ascending)