Indexer-Supported Collection in C#

Indexer is a faster way to search a list / collection in C#, no looping is necessary.

Classes that support indexer:

  • Array []
  • List<T>
  • Dictionary<Key, Value>
  • ILookup<Key, Value>

Classes that don’t support indexer:

  • IEnumerable<T>
  • HashSet<T>
  • ICollection<T>

For classes that don’t support indexer, there’s ElementAt LINQ extension method.

Why Must Extension Methods Be Declared in a Static Class?

Some possible answers:

  • The purpose of Extension Methods is to make LINQ work and LINQ only needs extension methods to be in a static, non-generic, non-nested class.
  • Easier for compiler to work with. Compiler and VS’s Intellisense can easily locate the methods.
  • Grouping the helper methods together.


Mocking Generic Method with NSubstitute

The generic method:

public interface ICacheService
    T Get<T>(string id);

User object in NSubstitute to mock the generic method.

private ICacheService MockICacheService()
    var service = Substitute.For<ICacheService>();

    // Return Models
    object returnForAny = null;

    // Mock

    return service;

Azure Storage Blob Listing Query with Search Pattern

Azure Storage blob is not behaving like files and folders in your local computer, albeit looking like one. So, there’s no support for search pattern, such as *.txt

The solution is to write your own search pattern.


public static String WildCardToRegular(String value) {
    return "^" + Regex.Escape(value).Replace("\\*", ".*") + "$";

Then, using it in Listing the blob:

var blobList = await container.ListBlobsSegmentedAsync(blobFilePath, true, BlobListingDetails.None, 1000, token, null, null);
var items = blobList.Results.Select(x => x as CloudBlockBlob);

// Filter items by search pattern, if specify
if (!string.IsNullOrEmpty(searchPattern))
    items = items.Select(i =>
        var filename = Path.GetFileName(i.Name);
        if (Regex.IsMatch(filename, WildCardToRegular(searchPattern), RegexOptions.IgnoreCase))
            return i;
	return null;