我想有可能不止一个用户使用一台计算机,并且多个用户可以使用一台特定的计算机。在这种情况下,拥有一个保存用户与计算机相关信息的类可能会更简单。然后,您可以创建该类的实例列表来保存整个信息集,并且作为列表,您可以使用 LINQ 轻松查询它,如下所示:
Option Infer On
Module Module1
Dim computerUsers As New List(Of ComputerUser)
Class ComputerUser
Property ComputerName As String
Property UserName As String
End Class
Sub CreateTestData()
computerUsers = New List(Of ComputerUser)
computerUsers.Add(New ComputerUser With {.ComputerName = "PC1", .UserName = "Fred"})
computerUsers.Add(New ComputerUser With {.ComputerName = "PC2", .UserName = "Jim"})
computerUsers.Add(New ComputerUser With {.ComputerName = "PC3", .UserName = "Jane"})
computerUsers.Add(New ComputerUser With {.ComputerName = "PC1", .UserName = "Jim"})
End Sub
Sub Main()
CreateTestData()
Dim pcName = "PC1"
Dim thisPcUsers = computerUsers.Where(Function(x) x.ComputerName = pcName).Select(Function(y) y.UserName).ToList()
Console.WriteLine(pcName & " is used by: " & String.Join(", ", thisPcUsers))
Dim user = "Jim"
Dim thisUserPCs = computerUsers.Where(Function(x) x.UserName = user).Select(Function(y) y.ComputerName).ToList()
Console.WriteLine(user & " uses computers: " & String.Join(", ", thisUserPCs))
Console.ReadLine()
End Sub
End Module
哪个输出
PC1 is used by: Fred, Jim
Jim uses computers: PC2, PC1
编辑+1 给赛斯,我在写这篇文章时没有看到他的回答。
编辑 2您可以通过各种方式使用 LINQ,例如获取名称以“J*”开头的用户:
Dim partialName = "J*"
Dim usersWithWildcard = computerUsers.Where(Function(x) x.UserName Like partialName).ToList()
Console.WriteLine("Users starting with " & partialName)
For Each u In usersWithWildcard
Console.WriteLine(u.UserName)
Next