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).