从集合中删除项目的最佳做法
Best practice to delete item from collection
我有一个 class 这样的
Public Class Car
Public Property Brand As String
Public Property Model As String
Public Property Horsepower As Integer
End Class
并从这个 class 中创建了一个对象集合
Dim myCarCollection As List(Of Car) = New List(Of Car) From {
New Car() With {.Brand = "VW", .Model = "Golf", .Horsepower = "100"},
New Car() With {.Brand = "Mercedes", .Model = "C220", .Horsepower = "110"},
New Car() With {.Brand = "Porsche", .Model = "911", .Horsepower = "341"}}
现在,例如我想删除品牌不是 VW 且马力小于 300 的所有汽车。"best" 方法是什么?我看到该集合有类似 myCarCollection.Where
的东西,有人可以解释一下如何做到这一点吗?
编辑:我知道如何用 for
/foreach
来做,但我在想一个更聪明的方法。
您可以使用 RemoveAll
移除不满足条件的汽车
myCarCollection.RemoveAll(Function(x) x.Brand <> "VW" AndAlso
x.Horsepower < 300)
当您将汽车添加到集合中时,由于 Option Strict set to Off,请不要使用 VB 编译器提供的自动转换。从长远来看运行这个选项弊大于利。
您可以使用 RemoveAll
:
myCarCollection.RemoveAll(Function(c As Car) c.Brand <> "VW" AndAlso
c.Horsepower < 300)
我有一个 class 这样的
Public Class Car
Public Property Brand As String
Public Property Model As String
Public Property Horsepower As Integer
End Class
并从这个 class 中创建了一个对象集合
Dim myCarCollection As List(Of Car) = New List(Of Car) From {
New Car() With {.Brand = "VW", .Model = "Golf", .Horsepower = "100"},
New Car() With {.Brand = "Mercedes", .Model = "C220", .Horsepower = "110"},
New Car() With {.Brand = "Porsche", .Model = "911", .Horsepower = "341"}}
现在,例如我想删除品牌不是 VW 且马力小于 300 的所有汽车。"best" 方法是什么?我看到该集合有类似 myCarCollection.Where
的东西,有人可以解释一下如何做到这一点吗?
编辑:我知道如何用 for
/foreach
来做,但我在想一个更聪明的方法。
您可以使用 RemoveAll
移除不满足条件的汽车myCarCollection.RemoveAll(Function(x) x.Brand <> "VW" AndAlso
x.Horsepower < 300)
当您将汽车添加到集合中时,由于 Option Strict set to Off,请不要使用 VB 编译器提供的自动转换。从长远来看运行这个选项弊大于利。
您可以使用 RemoveAll
:
myCarCollection.RemoveAll(Function(c As Car) c.Brand <> "VW" AndAlso
c.Horsepower < 300)