搜索列表中的对象

时间:2012-08-01 15:36:55

标签: vb.net predicate

我有一个对象列表,我想搜索它以查看myobject.articleID是否与给定的articleID匹配。从我收集到的内容.Find(Of T)是最好的解决方法,但是我在实现它时遇到了一些困难。这是我到目前为止的一些代码:

<WebMethod()> _
Public Function SetTagOnFavorite(ByVal articleID As Integer, ByVal tagtext As String, ByVal mobileGUID As String) As AddTagResult
    Dim result As New AddTagResult
    Dim userID As Long = GetUserIDByMobileGUID(mobileGUID)


    If userID > 0 Then
        Dim pageNum As Integer = 1
        Dim pageLen As Integer = 500 'arbitrarily large number
        Dim savedArticleList As New List(Of SimpleArticle)
        savedArticleList = GetSavedArticles(mobileGUID, pageNum, pageLen)

        If savedArticleList.Find(Function( m As SimpleArticle) m.articleID = articleID)


            Dim lq As New lqDFDataContext
            Dim var = lq.web_AddTagToArticle(userID, articleID, tagtext).ToList()

            If var.Any() Then
                Dim vRes = var.First()
                result.articletagID = vRes.articletagID
                result.newarticletag = vRes.newarticletag
                result.newusertag = vRes.newusertag
                result.usertagID = vRes.usertagID
                result.resultinfo = "Success."

            End If
       End If  
    Else
        result.resultinfo = STR_NoUserIDMostLikelyTheSessionTimedOut
    End If
    Return result
End Function

我得到的错误是,“SimpleArticle类型的值无法转换为布尔值”。

2 个答案:

答案 0 :(得分:4)

因为Find(Of返回找到的对象,所以需要更改此行:

If savedArticleList.Find(Function( m As SimpleArticle) m.articleID = articleID)

If savedArticleList.Find(Function( m As SimpleArticle) m.articleID = articleID) IsNot Nothing 

或者如果您需要找到的项目,请将Find的结果存储在本地变量中。

答案 1 :(得分:3)

您可以进一步优化@ competent_tech的答案:

If savedArticleList.Any(Function(m) m.articleID = articleID))