An alternative to writing complex queries for entities already in memory

Introduction

There’s been a couple times where I have struggled to simply pull in data regarding some business entity and its association to other entities without bloating out a class definition for a business object.

Specifically, I was building an inventory system and discovered a pattern for looking up information without being loss in complicated query syntax.

Let’s just call it the Lookup Pattern.

This pattern is a single class that is a container of dictionaries that uses a naming convention for the dictionaries it contains.

The naming convention is the following:

<key>To<value>

Yes. It’s that simple.

Implementation

public class Lookup

{

public Dictionary<string, decimal> StockCodeToTotalSupplyQty { get; set; }

public Dictionary<string, decimal> StockCodeToTotalDemandQty { get; set; }

public Dictionary<string, HashSet<Job>> JobIdToJob { get; set; }

public Dictionary<string, HashSet<Job>> QuoteIdToJobs { get; set; }

public Dictionary<int, HashSet<Job>> DaysRemainingToCompletedJobs { get; set; }

public Dictionary<string, HashSet<string>> StockCodeToStockAlternatives { get; set; }

public void Clear()

{

. . .

}

}

Usage


var stockCodeWithAlternatives = new List<string>() { demandRequirements.StockCode };

HashSet<string> alternativeStockCodes = null;
var exists = demandRequirements.Lookup.StockCodeToStockAlternatives.TryGetValue(demandRequirements.StockCode, out alternativeStockCodes);

if (exists)
{
    stockCodeWithAlternatives.AddRange(alternativeStockCodes);
}

 

Conclusion

In conclusion, I have provided a simple pattern for managing potentially complex queries using a simple alternative (i.e. Lookup).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: