【问题标题】:Visual Basic Find String in List Of ObjectVisual Basic 在对象列表中查找字符串
【发布时间】:2016-12-17 01:21:29
【问题描述】:

问候。我目前有点卡在Object (int,string)的列表中查找字符串@

我想检查字符串是否已经包含在列表中 - 如果没有添加它。

常规的<List>.Contains() 不起作用,因为我在插入之前初始化了一个新对象。

这是我的代码:

Dim command = New SqlCommand(query, connection)
        Dim reader = command.ExecuteReader()
        While reader.Read

            Dim projID = reader.Item("DB_ID")
            Dim projName = reader.Item("Project")
            Dim proj = New KMProject(projName, projID)
            projList.Add(proj)

        End While
        reader.Close()
 =============================== ProjList having some items already =====================================
        query = ...

            command = New SqlCommand(query, connection)
            reader = command.ExecuteReader()
            While reader.Read

            Dim projID = reader.Item("DB_ID")
            Dim projName = reader.Item("Project")
            Dim proj = New KMProject(projName, projID)
===============Below this section im stuck while verifying if this String is already in the List ===================================
            For Each p In projList
                If projList.Contains() Then
                Else

                    projList.Add(proj)
                End If
            Next

【问题讨论】:

    标签: vb.net list contains basic


    【解决方案1】:

    在我看来,你最好的选择是 LINQ:

    If Not progList.Any(Function(x) x.Name = "Your string to check") Then
        /*Add the thing*/
    End If
    

    别忘了你必须添加 Imports 语句:

    Imports System.Linq;
    

    【讨论】:

    • 也给他“using”/“imports”声明,我会赞成的。
    • "使用 System.Linq;"在 C# 中。
    • 哦,我明白了,确实有道理
    • 该死!我刚刚意识到整个都在 VB 中......我在这两个方面都做了很多工作,以至于它们现在是一回事。
    • 有人对你投了反对票。但我现在正在投票。给他不区分大小写的字符串检查比较,你会得到一个很好的答案。
    【解决方案2】:

    你可以使用 Linq...

    For Each p in projlist
        If Not projlist.Any(Function(pl) (pl.ID = proj.ID)) Then prodlist.Add(proj)
    Next
    

    (将 ID 替换为对象的属性名称)

    【讨论】:

    • 添加他需要的 using/imports 语句............对于“Any”......并提供不区分大小写的等号检查版本...... .我会投赞成票。
    • @granadaCoder:我没有包含 import 语句,因为上面的代码将在没有它的情况下编译,并且在 OP 的帖子中他说 proj 是 Object (int,string),我正在比较整数我的答案中的 ID 所以大小写无关
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多