RSS

Monthly Archives: September 2017

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.

Advertisements
 
Leave a comment

Posted by on September 28, 2017 in General

 

Tags: , ,

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.

Sources:
https://stackoverflow.com/questions/3930335/why-are-extension-methods-only-allowed-in-non-nested-non-generic-static-class

https://stackoverflow.com/questions/7163823/why-must-c-sharp-extension-methods-be-defined-in-static-classes

 
Leave a comment

Posted by on September 20, 2017 in General

 

Tags: ,

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
    service.Get<object>(Arg.Any<string>()).ReturnsForAnyArgs(returnForAny);

    return service;
}

 
Leave a comment

Posted by on September 13, 2017 in General

 

Tags: ,

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.

from https://stackoverflow.com/questions/30299671/matching-strings-with-wildcard


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;
    }).ToList();
}

 
Leave a comment

Posted by on September 9, 2017 in General

 

Tags: ,

 
%d bloggers like this: