For each loop not skipping items
I have a for each loop in vb.net for this particular exam开发者_运维问答ple there are 2 items in list but after the first item the loop exits are there errors in the code
Public Function findUserID(ByVal list As List(Of KeyValuePair(Of String, String)), ByVal value As String)
Dim id As String = String.Empty
For Each kvp In list
If (kvp.Value = value) Then
id = kvp.Key
End If
Next
Return id
End Function
Try to use this:
dim kvp as KeyValuePair
kvp = list.Find(p=>p.Value = value))
if kvp = null then return "" else return kvp.Key
One user told me to modify it in this way:
dim kvp = list.Find(Function(e) e.Value = value)
If kvp Is Nothing Then Return "" Else Return kvp.Key
Sorry if this code has some error, but I cannot try and I usually write in C#.
So my code (in C#) would be:
KeyValuePair kvp = list.Find(p=>p.Value == value));
return kvp == null ? "" : kvp.Key;
Why you have the id variable and don't return the Key directly if you found a valid? So the collection will loop through all KeyValuePairs and not stop on any results.
Public Function FindUserID(ByVal list As List(Of KeyValuePair(Of String, String)), ByVal value As String)
For Each kvp In list
If (kvp.Value = value) Then
Return kvp.Key
End If
Next
End Function
But thats not the error, did you debug the method and verified that there are more than one KeyValuePairs in the list?
精彩评论