Search code examples
vb.netexchangewebservices

VB.NET Loop Collection And Get Value


I'm using EWS to loop through some attachments, however if I come across an email that has multiple attachments I only want to download a particular attachment.

To do this I figured I could just test to see if the AttachmentCollection Contains the particular attachment name and only download that attachment.

How can I loop through AttachmentCollection and test each name of the Attachment?

I can't do an AttachmentCollection.Contains because it contains a Collection of Attachments and not the name of the attachments themselves.


Solution

  • I'm not completely familiar with the types involved by I believe that that AttachmentCollection implements IEnumerable(Of T), which means you can use some LINQ on it. You can test for and get the attachment using something like this:

    Dim attachment = myAttachmentCollection.FirstOrDefault(Function(a) a.Name = someValue)
    
    If attachment IsNot Nothing Then
        'A match was found and attachment refers to it.
    End If
    

    Not sure what the item type is so you may not have a Name property but the principle is the same.

    EDIT:

    For the record, the equivalent of Contains would be Any:

    If myAttachmentCollection.Any(Function(a) a.Name = someValue) Then
    

    That's fine if all you want to know is whether a match exists but, if you want to get the matching item too, you wouldn't use Any first because then you'd be enumerating twice. FirstOrDefault does pretty much the same as Any except it returns the matching item if one is found or Nothing if no matches are found rather than returning True if a match is found or False if no matches are found.