How can I find a strongly typed list for a string?

How can I "search" through a strongly typed list for a string?

I'm trying .Contains (TheString) however it reports errors. Cannot overlay object of type "System.String" on type "o7thCrawler.Typing.ImportantTyping"

Here is the code:

Public Class LinkTyping
    Public Property Url As String
    Public Property Title As String
    Public Property Content As String
End Class

If Not (_InternalUrls.Contains(_Url & _Link)) Then
    _InternalUrls.Add(New Typing.LinkTyping() With {
                                                          .Url = _Url & _Link,
                                                          .Content = Item.Value,
                                                          .Title = If(Item.Attribute("title") IsNot Nothing,
                                                                      Item.Attribute("title").Value,
                                                                      Nothing)
                                                      })
End If

      

+3


source to share


3 answers


You are trying to translate 2 types into one list ...

What type InternalUrls

?

It:

If Not (_InternalUrls.Contains(_Url & _Link)) Then

      

Implies it IList(Of String)

but this:

_InternalUrls.Add(New Typing.LinkTyping() With {

      



Then it tries to add a new instance of the LinkTyping class to it ...

How about something like ...

Do InternalUrls

be aList(Of LinkTyping)

Then

Dim MyUrl = String.Format("{0}{1}", _Url, _Link)
If Not InternalURLs.Any(function(x) x.Url = MyUrl) Then
    InternalURLs.Add(New Typing.LinkTyping() With {<Blah>})

End If

      

NB. The solution above assumes the URLs will be the same for matching purposes (as in your example, except for the overloaded comparison operator) - you can use a case insensitive comparison ...

If Not InternalURLs.Any(function(x) String.Equals(x.Url, MyUrl, StringComparison.OrdinalIgnoreCase)) Then

      

+2


source


Assuming _InternalUrls is a List, then the Contains method will use your Equals objects' implementation to decide if the object is already in the collection. Thus, one option would be to overload Equals for your class.



MSDN link

+1


source


It's actually quite easy to do with a lambda expression:

If _InternalUrls.Any(Function(l) l.Url = _Url) Then
    ' Do Add Logic Here

      

The following should be at the top of the screen:

Imports System.Linq

      

(Changed FirstOrDefault to use Any)

+1


source







All Articles