Home > Back-end >  Searching a multi-dimensional array with VB.Net to count occurrences of a string
Searching a multi-dimensional array with VB.Net to count occurrences of a string

Time:09-13

I have Dictionary defined as:

Private cdEmailsUploaded As New ConcurrentDictionary(Of String, Boolean)

The string contains the fullpath to an email file (MSG) and I want to create a function that returns a count of those that contain a given string in their path e.g "ProjectX".

I have assumed, possibly incorrectly, that it would be best to convert the Dictionary into an Array and then search it for the string and count the results. If there is a better way then please let me know.

The problem is that I can't get my head around the syntax to get the embedded function to search the string part of the array and not the Boolean.

What I have at the moment is:

Function QtyUploadedToLocation(sFind As String) As Integer
        Dim emailsArr = cdEmailsUploaded.ToArray
        Dim result As String() = Array.FindAll(emailsArr, Function(s) s.Key.StartsWith(sFind))
        Return result.Length
    End Function

The error I'm getting is:

Value of type 'KeyValuePair(Of String, Boolean)()' cannot be converted to 'String()' because 'KeyValuePair(Of String, Boolean)' is not derived from 'String'.

CodePudding user response:

The signature of Array.FindAll is:

Public Shared Function FindAll(Of T) (array As T(), match As Predicate(Of T)) As T()

That means that for a dictionary type, it's working in KeyValuePair(Of TKey, TValue) throughout, and in particular, the result is an array of key/value pairs, not an array of string.

If you just want the count, you could a) fix the intermediate type, b) use type inference to avoid having to say what the type is (if you have Option Infer On), or c) just return the count directly, i.e.

Return Array.FindAll(emailsArr, Function(kvp) kvp.Key.StartsWith(sFind)).Length

If you want the array of strings for further processing, you can use the Linq Select function to get that sequence, i.e.

Dim matchingKeys = _
    Array.FindAll(emailsArr, Function(kvp) kvp.Key.StartsWith(sFind)) _
         .Select(Function(kvp) kvp.Key)

This will be an IEnumerable(Of String), you could use ToArray if you need it as an array or just leave it as-is if you want to do some other processing on it.

  • Related