0

Bit of a wordy title, but I am not sure how else to phrase it. I am doing some work on Azure Storage Account Blobs, and I want to get the Metadata for each blob, which is done by calling a method on that object. Currently, I am using a looping construct to call the method like so

IEnumerable<IListBlobItem> listOfBlobs =
    cloudBlobContainer.ListBlobs(blobName, true, BlobListingDetails.Snapshots);

foreach (IListBlobItem blobItem in listOfBlobs)
{                    
    CloudBlockBlob theBlob = blobItem as CloudBlockBlob;
    theBlob.FetchAttributes();                   
    Console.WriteLine("Snapshot Uri: {0}", theBlob.SnapshotQualifiedUri.AbsoluteUri);
}

I am wondering if there is a more elegant way of doing this. I know that I can typically do

listOfBlobs.ForEach(item => SomeMethod(item))

But since FetchAttributes is a void method, it will fail at build time because it needs to return an IEnumerable<T> to use foreach. My question is: how do I call FetchAttributes() for all items in the list? Am I better off using the loop? Is there some Linqy way of doing it?

ardila
  • 1,277
  • 1
  • 13
  • 24
Isaac Levin
  • 2,809
  • 9
  • 49
  • 88
  • 1
    Use the loop. Much clearer. – Maarten Jun 30 '16 at 14:10
  • You can use `var` when you declare `listOfBlogs`, saves some space. Also you can do `foreach (CloudBlockBlob blobItem in listOfBlobs) {` to eliminate the casting in the foreach-block, also saves some space. – Maarten Jun 30 '16 at 14:12
  • 1
    At the risk of splitting hairs, why "Call Virtual Method" and not just "Call Method?" A method is a method. The caller doesn't know or care whether the target inherits or implements it. – Scott Hannen Jun 30 '16 at 14:15
  • 3
    `Is there some Linqy way of doing it?` - Linq is for **querying**, not for causing side-effects. – Maarten Jun 30 '16 at 14:23
  • To expound on Maarten's point, here's an [argument](https://blogs.msdn.microsoft.com/ericlippert/2009/05/18/foreach-vs-foreach/) **against** using a *"Linqy"* construct instead of a loop by Eric Lippert. Related question: http://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for-ienumerablet – ardila Jun 30 '16 at 14:27
  • Second that. Resharper suggests converting ForEach to a LINQ expression and "everyone is doing it," but it gives the impression that something is wrong with `foreach`. I've seen code that converts `IEnumerable` to `List` just so that it can use `ForEach` instead of `foreach`. Awesome adjective, "Linqy." – Scott Hannen Jun 30 '16 at 14:57
  • Also, you could avoid the question entirely by passing in "BlobListingDetails.Snapshots | BlobListingDetails.Metadata" into the ListBlobs call (or BlobListingDetails.All). This should fetch the metadata without having to call FetchAttributes(), and should be much more performant. – Adam Sorrin - MSFT Jun 30 '16 at 21:12

0 Answers0