Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

vb.net - For each loop not skipping items

I have a for each loop in vb.net for this particular example 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...