计算集合中有多少计算机对象具有MAC地址的最快/最有效方法是什么(即计算机.MACAddress<>“”)
<Serializable>
Public Class Computer
Public Property Name As String
Public Property FQDN As String
Public Property Path As String
Public Property GUID As String
Public Property MACAddress As String
Public Property IPAddress As Net.IPAddress
End Class
<Serializable>
Public Class ComputerCollection
Inherits Collection(Of Computer)
End Class
目前我正在使用LINQ:
Dim macCount = From comp In computers Where comp.MACAddress <> "" Select comp
ssMACDisc.Text = macCount.Count.ToString + " MAC Addresses Discovered"
提前致谢
答案 0 :(得分:1)
LINQ也使用循环。但是你应该更喜欢通常最易阅读的方式。
Dim nonEmptyMacs = From comp In computers
Where Not String.IsNullOrEmpty(comp.MACAddress)
Dim countNonEmptyMacs = nonEmptyMacs.Count()
如果您需要更高效的内容,可以使用Lookup(Of Tkey, TElement)
来计算所有null / empty mac。您只能通过ToLookup
初始化查询。如果集合没有经常更改,您可以将其保留在以后可以访问的字段中。也许你也可以从添加新计算机的方法中重新创建它。您需要一个自定义IEqualityComparer(Of Computer)
,它将null和空mac等同于:
Public Class ComputerMacComparer
Implements IEqualityComparer(Of Computer)
Public Function Equals1(x As Computer, y As Computer) As Boolean Implements System.Collections.Generic.IEqualityComparer(Of Computer).Equals
If x Is Nothing OrElse y Is Nothing Then
Return False
End If
If String.IsNullOrEmpty(x.MACAddress) AndAlso String.IsNullOrEmpty(y.MACAddress) Then Return True
Return x.MACAddress = y.MACAddress
End Function
Public Function GetHashCode1(obj As Computer) As Integer Implements System.Collections.Generic.IEqualityComparer(Of Computer).GetHashCode
If String.IsNullOrEmpty(obj.MACAddress) Then Return 0
Return obj.MACAddress.GetHashCode()
End Function
End Class
好处:您可以将此类用于许多其他LINQ方法,例如GroupBy
或Intesect
。
我已使用此示例数据:
Dim computers As New ComputerCollection
computers.Add(New Computer With {.MACAddress = ""})
computers.Add(New Computer With {.MACAddress = nothing})
computers.Add(New Computer With {.MACAddress = "1"})
computers.Add(New Computer With {.MACAddress = "2"})
computers.Add(New Computer With {.MACAddress = "3"})
computers.Add(New Computer With {.MACAddress = Nothing})
如您所见,有三台计算机具有null或empty-mac。
您需要一个示例性的&#34; Null&#34; - 计算机,以后可以使用:
Dim nullComp = New Computer With {.MACAddress = Nothing}
以下是创建查询和计算所有计算机所需的唯一代码:
Dim macLookup = computers.ToLookup(Function(comp) comp, New ComputerMacComparer())
Dim countNull = macLookup(nullComp).Count() ' 3
这应该更有效,因为查找类似于Dictionary
。如果未包含密钥,则返回空序列。