如何在列表中找到特定项目(T)?

时间:2014-07-18 01:27:58

标签: vb.net visual-studio-2010

Public Class B1
    Public G2 As New List(Of Person)
End Class
Public Class Person
    Public Property PerId As Integer
    Public Property FirstName As String
    Public Property LastName As String
End Class
Public Class All4One
    Public Property ID As Integer
    Public Property Dept As String

    Public Overrides Function ToString() As String
        Dim _pers As New Person
        _pers = G2.Item(??)
        Return _pers.FirstName & " " & _pers.LastName
    End Function
End Class

这是我被挂断的地方。我想在G2中找到索引(= to ??),其中_pers.PerId = ID。

感谢您的协助。 GregV

1 个答案:

答案 0 :(得分:3)

这是您需要做的 - 使用LINQ扩展名。您不必这样做,因为您可以根据需要手动迭代列表。  但我不知道你将要用它来搜索它?而且您使用ToString()完全错误 - 只有班级成员才能拥有Tostring Return pers.FirstName & " " & pers.LastName。从技术上讲,它可以如下:

Public Class All4One
    Private _perId as integer 'I added it to use for search as an example

    Public Property ID As Integer
    Public Property Dept As String

    'WARNING!!!! BAD DESIGN
    Public Overrides Function ToString() As String
        Dim pers As Person = G2.FirstOrDefault(function(p) p.PerId = _perId)
        If pers isNot Nothing Then            
           Return pers.FirstName & " " & pers.LastName
        Else
           'return whatever you want
           Return "No Person found"
        End If
    End Function
End Class

你需要添加一些东西来搜索人物。此外,如果您的合同中只能在列表中找到一个唯一的PersID,则可以使用SingleOrDefault而不是FirstOrDefault来缩短几毫秒。