Home > OS >  Using .Contains with List(Of Structures
Using .Contains with List(Of Structures

Time:05-28

This code works - I get true, then false

Dim listDates As New List(Of Date)
listDates.Add("2022-03-15")
Debug.Print(listDates.Contains("2022-03-15"))
Debug.Print(listDates.Contains("2022-03-16"))

If, instead of simple list of dates, I make it a list of structures, is it possible to do a similar test without a loop?

Public Structure FileData
    Public FileName As String
    Public FileDate As Date
    Public FileType As String
End Structure

Dim listDates2 As New List(Of FileData)
Dim oneFileData As New FileData
oneFileData.FileDate = "2022-03-15"
listDates2.Add(oneFileData)
Debug.Print(listDates2.Contains("2022-03-15"))
Debug.Print(listDates2.Contains("2022-03-16"))

The last 2 lines give me "Value of type 'string' cannot be converted to 'FileData' syntax errors which is understandable. But without looping is there a way to look in the FileDate element of the Structures to find a matching element? Something like these pseudocode attempts (which don't work either):

Debug.Print(listDates2.FileDate.Contains("2022-03-15"))
Debug.Print(listDates2(FileDate).Contains("2022-03-15"))

CodePudding user response:

The Any extension method is what you want. The Contains method basically says "does the list contain an item equal to this" while the Any method says "does the list contain an item that satisfies this condition". In your case:

Debug.Print(listDates2.Any(Function(fd) fd.FileDate = "2022-03-15"))

You could also do this:

Debug.Print(listDates2.Select(Function(fd) fd.FileDate).Contains("2022-03-15"))

CodePudding user response:

As John pointed out, I wasn't used Option Strict On. So the code below uses Option Strict On and also uses John's answer, changed slightly to also meet the Option Strict On requirements.

It now works fine!

Public Structure FileData
    Public FileName As String
    Public FileDate As Date
    Public FileType As String
End Structure

Dim listDates2 As New List(Of FileData)
Dim oneFileData As New FileData
oneFileData.FileDate = CDate("2022-03-15")
listDates2.Add(oneFileData)
Debug.Print(CType(listDates2.Any(Function(fd) fd.FileDate = CDate("2022-03-15")), String))
Debug.Print(CType(listDates2.Any(Function(fd) fd.FileDate = CDate("2022-03-16")), String))
  • Related