Để sắp xếp một List trong C#, sử dụng phương thức Sort().
Các bước:
- Tạo List:
List<string> myList = new List<string>(); - Thêm phần tử:
Add() - Sắp xếp:
myList.Sort();
Ví dụ hoàn chỉnh
using System;
using System.Collections.Generic;
class Demo
{
static void Main()
{
List<string> myList = new List<string>();
myList.Add("Audi");
myList.Add("BMW");
myList.Add("Chevrolet");
myList.Add("Hyundai");
myList.Sort();
foreach (string value in myList)
{
Console.WriteLine(value);
}
}
}
Kết quả
Audi
BMW
Chevrolet
Hyundai
Lưu ý: Sort() sắp xếp theo thứ tự tăng dần mặc định (alphabetical cho string, numeric cho số). Để sắp xếp giảm dần, dùng myList.Reverse() sau khi Sort hoặc triển khai IComparer.