Cho rằng bạn có 1 danh sách các countries và cities chưa được sắp xếp, giờ mình sẽ hướng dẫn bạn sắp xếp chúng theo thứ tự tăng dần (mặc định) theo countries, tiếp theo đó sắp xếp theo cities.
Tạo 1 class City đơn giản:
CS:
public class City
{
public string Name { get; set; }
public string Country { get; set; }
}
Sau đó khởi tạo danh sách các cities
List <City> cities = new List<City>
{
new City{ Country="Vietnam",Name="Ha Noi"},
new City{ Country="USA",Name="New York"},
new City{ Country="Tokyo",Name="Japan"},
new City{ Country="Milan",Name="Spain"},
new City{ Country="Amsterdam",Name="Netherland"},
new City{ Country="Vietnam",Name="Bac Giang"},
};
Hiển thị lên màng hình các danh sách đó chưa được sắp xếp:
Console .WriteLine("******************* Before order *******************");
foreach (var item in cities)
{
Console.WriteLine(item.Name + " of " + item.Country);
}
Dùng OrderBy extension method để sắp xếp theo thứ tự tăng dần theo country
Console .WriteLine("******************* After order by country *******************");
cities = cities.OrderBy(c => c.Country).ToList<City>();
foreach (var item1 in cities)
{
Console.WriteLine(item1.Name + " of " + item1.Country);
}
Tiếp tục Order cho city
Console .WriteLine("******************* After order by country the name *******************");
cities = cities.OrderBy(c => c.Country).ThenBy(n => n.Name).ToList<City>();
foreach (var item2 in cities)
{
Console.WriteLine(item2.Name + " of " + item2.Country);
}
VB.NET:
Module Module1
Sub Main()
Dim cities As New List(Of City)() From _
{
New City With {.Country = "Vietnam", .Name = "Ha Noi"},
New City With {.Country = "USA", .Name = "New York"},
New City With {.Country = "Tokyo", .Name = "Japan"},
New City With {.Country = "Milan", .Name = "Spain"},
New City With {.Country = "Amsterdam", .Name = "Netherland"},
New City With {.Country = "Vietnam", .Name = "Bac Giang"}
}
Console.WriteLine("******************* Before order *******************")
For Each item In cities
Console.WriteLine(item.Name + " of " + item.Country)
Next
cities = cities.OrderBy(Function(c) c.Country).ToList()
Console.WriteLine("******************* After order by country *******************")
For Each item1 In cities
Console.WriteLine(item1.Name + " of " + item1.Country)
Next
Console.WriteLine("******************* After order by country the name *******************")
cities = cities.OrderBy(Function(c) c.Country).ThenBy(Function(n) n.Name).ToList()
For Each item2 In cities
Console.WriteLine(item2.Name + " of " + item2.Country)
Next
Console.Read()
End Sub
Class City
Public Property Name As String
Public Property Country As String
End Class
End Module
checkout our code: http://code2code.googlecode.com/svn/trunk/MultiOrderInNet