在VB.NET中 遍历List找到某个字段的某个值对应的另一个字段的某个值
时间: 2024-04-24 08:26:06 浏览: 280
在VB.NET中,你可以使用LINQ查询语句或循环遍历来遍历一个List,并找到满足特定条件的元素。然后,你可以获取该元素的另一个字段的值。
以下是使用LINQ查询语句的示例代码:
```vb
' 假设你有一个名为Person的类,其中包含字段Name和Age
Public Class Person
Public Property Name As String
Public Property Age As Integer
End Class
' 创建一个List<Person>对象并添加一些元素
Dim people As New List(Of Person)()
people.Add(New Person() With {.Name = "Alice", .Age = 25})
people.Add(New Person() With {.Name = "Bob", .Age = 30})
people.Add(New Person() With {.Name = "Charlie", .Age = 35})
' 定义要查找的字段和值
Dim targetName As String = "Bob"
Dim targetAge As Integer
' 使用LINQ查询语句找到满足条件的元素,并获取另一个字段的值
Dim result = From person In people
Where person.Name = targetName
Select person.Age
' 检查是否找到了匹配的元素
If result.Any() Then
targetAge = result.First()
Console.WriteLine("Found {0} with age {1}", targetName, targetAge)
Else
Console.WriteLine("No match found for {0}", targetName)
End If
```
在上述示例代码中,我们创建了一个包含Person对象的List,并定义了要查找的字段和值。然后,我们使用LINQ查询语句从List中筛选出满足条件的元素,并选择另一个字段的值。如果找到了匹配的元素,我们将其赋值给`targetAge`变量,并进行相应的操作。
你也可以使用循环遍历的方法来实现相同的功能:
```vb
For Each person In people
If person.Name = targetName Then
targetAge = person.Age
Console.WriteLine("Found {0} with age {1}", targetName, targetAge)
Exit For
End If
Next
If targetAge = 0 Then
Console.WriteLine("No match found for {0}", targetName)
End If
```
这里使用了`For Each`循环遍历List中的元素,判断是否满足条件,并获取另一个字段的值。如果找到了匹配的元素,我们将其赋值给`targetAge`变量,并进行相应的操作。
请根据你的具体情况选择适合的方法来遍历List并找到相应的值。希望对你有所帮助!如有任何进一步问题,请随时提问。
阅读全文
相关推荐


















