萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

VB.NET List(Of T) 進階用法:ForEach、FindAll、Sort 實戰

建立強型別清單

Public Class Bottle
    Public Property Brand As String
    Public Property Name As String
    Public Property Category As String
    Public Property Size As Decimal
    Public Sub New(b As String, n As String, c As String, s As Decimal)
        Brand = b : Name = n : Category = c : Size = s
    End Sub
End Class

Dim Cabinet As New List(Of Bottle)
Cabinet.Add(New Bottle("Castle Creek", "Uintah Blanc", "Wine", 750))
Cabinet.Add(New Bottle("Zion Canyon Brewing", "Springdale Amber Ale", "Beer", 355))
Cabinet.Add(New Bottle("Spanish Valley Vineyards", "Syrah", "Wine", 750))
Cabinet.Add(New Bottle("Wasatch Beers", "Polygamy Porter", "Beer", 355))
Cabinet.Add(New Bottle("Squatters Beer", "Provo Girl Pilsner", "Beer", 355))

1. ForEach:遍歷執行動作

Sub DisplayBottle(b As Bottle)
    Console.WriteLine(b.Brand & " - " & b.Name)
End Sub

Cabinet.ForEach(AddressOf DisplayBottle)

2. FindAll:依條件篩選回傳新清單

Function IsBeer(b As Bottle) As Boolean
    Return b.Category = "Beer"
End Function

Dim beers As List(Of Bottle) = Cabinet.FindAll(AddressOf IsBeer)
For Each b In beers
    Console.WriteLine(b.Brand & " - " & b.Name)
Next

3. Sort:自訂比較器重新排序原清單

Private Shared Function CompareByCategory(x As Bottle, y As Bottle) As Integer
    Return x.Category.CompareTo(y.Category)
End Function

Cabinet.Sort(AddressOf CompareByCategory)
For Each b In Cabinet
    Console.WriteLine(b.Category & " | " & b.Brand & " - " & b.Name)
Next

重點總結

  • `ForEach` 接受 `Action(Of T)` 委派,適合單純遍歷副作用(列印、寫入)。
  • `FindAll` 接受 `Predicate(Of T)`,回傳新 `List(Of T)`,原清單不變。
  • `Sort` 可傳 `Comparison(Of T)` 或 `IComparer(Of T)`,就地重排 原清單。
  • 善用 `AddressOf` 將具名方法轉為委派,程式碼清晰易維護。
copyright © 萬盛學電腦網 all rights reserved