我希望能够从数组中读取与我在另一个数组中的某个名称相关的一组特定行
例如:
名字数组中的我有" Ben"存储为名称,我想看看其他数组是否也包含名称" Ben"如果确实如此,它将添加每行的分数,其中" Ben"提到
其他阵列:
" Ben得到5" "纳什得到6" " Ben得到4" " Josh得到1"
因此它只会添加5和4来获得9
程序将把计算出的数字保存到列表中。
For Each n As String In commonNames 'for the example the commonNames array contains Ben"
If names.Contains(n) Then
'add each of their scores and divide by how many their are
End If
Next
Console.ReadLine()
For Each n As String In originames
'add each score to the user and divide by 1
任何帮助将不胜感激的家伙:)
答案 0 :(得分:1)
Dim data = {"Ben got 5", "Nash got 6", "Ben got 4", "Josh got 1", "Ziggy got 42"}
Dim names = {"Ben", "Ziggy"}
Dim results(names.Length - 1) As Int32
For Each item In data
For n As Int32 = 0 To names.Length - 1
' see if this item starts with name data
If item.StartsWith(names(n)) Then
' if so, parse out the value
Dim parts = item.Split(" "c)
results(n) += Int32.Parse(parts(parts.Length - 1))
Exit For
End If
Next
Next
' show contents of parallel arrays:
For n As Int32 = 0 To names.Length - 1
Console.WriteLine("{0} total = {1}", names(n), results(n))
Next
结果:
Ben total = 9
Ziggy总数= 42
如果数据最后可能包含非数字,请使用TryParse insteasd。
根据一系列相关问题,您应该认真考虑使用一些允许您将相关数据存储在一起的类。而不是一个数组中的名称和另一个数组中的得分/计数,一个类有助于将所有内容保持在一起。请参阅此答案中的Five Minute Intro To Classes and Lists。
使用简单的NameValuePair
实用程序类from this answer,代码实际上变得更简单(仅一个循环),名称和计数保持在一起:
Dim np As NameValuePair ' scratch var
Dim players As New List(Of NameValuePair) ' list
' add the names you are looking for to
' the list with 0 Score/Count
' not needed if they are in the list from code upstream
For Each n As String In names
players.Add(New NameValuePair(n, 0))
Next
For Each item In data
Dim parts = item.Split(" "c)
' is there a player name for this one?
np = players.FirstOrDefault(Function(w) w.Name = parts(0))
If np IsNot Nothing Then
np.Value += Int32.Parse(parts(parts.Length - 1))
End If
Next
' the data is together: print it
For Each np In players
Console.WriteLine("Name: {0} has {1} apples", np.Name, np.Value)
Next