我有一个对象列表,如下所示:
Public Class LineItem
Public Property Name As String
Public Property Weight As Int32
Public Property Expression As String
End Class
Private _lineItems As New List(Of LineItem)
我随机选择一个项目:
Public Function SelectItem(ByVal name As String) As LineItem
Dim items As List(Of LineItem) = CType(Rules.Where(Function(li As LineItem) li.Name = name.Remove("[", "]")).ToList, List(Of LineItem))
Dim totalWeight As Int32 = items.Sum(Function(li As LineItem) li.Weight)
If totalWeight > 0 Then
Dim sum As Int32 = 0
Dim index As Int32 = (BaseGrammar.Random.Next Mod totalWeight) + 1
For Each item As LineItem In items
sum += CInt(item.Weight)
If sum >= index Then
Return item
End If
Next
End If
Return Nothing
End Function
虽然这适用于小型列表,但是当列表变大时,显然效率非常低。我缺少哪种结构或方法可以提高效率?
答案 0 :(得分:1)
我认为你的功能很好,但是你认为你的代码经历了3次循环。首先取出字符,然后找到总和,然后捕获项目的子集。也许如果您通过删除初始Linq重做代码,您可以进行常规循环,您可以在其中修复Name属性并总结Weight。这将把你的时间减少33%