I have a backend table as shown below and I am reading it using ado.net.
I tried to convert this to a dictionary with key value pair, but I don’t know how to map keys and values so that when I read code 1 I can return its category name, and when I read 2 as code 3 as subcode I can read both its corresponding category and subcategory?(Say ex., Old, ThreeMonth).
Is there any other type/class available to acheive this functionality?
code Sub_Code Category Sub_Category
1 1 NEW NEW
2 1 Old OneMonth
2 2 Old TwoMonth
2 3 Old ThreeMonth
2 4 Old Ninemonth
5 4 APPOINTMENT APPOINTMENT MADE
9 4 Invalid LANGUAGE BARRIER
You have a number of options, depending on what operations you need to do with the data, how often it changes, etc. Some obvious ones are:
Nested Types
Create a custom type to hold your category and its sub-categories. This has the benefit that you can skip the sub-categories if there are none, and your data type can exactly map to your business object.
(I’d also consider a
KeyedCollectionhere that can extract theIdfrom aCategoryas the key directly.)The downside: its a bit more work to add or retrieve a subcategory because you have to do two lookups:
A 4-Tuple (quadruple?)
If your data structure rarely changes you can use a 4-field
Tuple<>:The biggest downside here is that it’s not indexed very well. You could alleviate that a bit, at the cost of even more complexity, by using two
Tuples(one key, one value):But IMO that gets kinda messy, and at that point I’d just go with a custom class.
Split Collections
Split up the category name and subcategories into separate collections: one holds the cateogory id -> name mapping, and the other holds the category id -> subcategory mapping:
This is more flexible than the
Tuplesolution but doesn’t involve a custom data type, so it’s a more “quick and dirty” solution. Also, if you commonly find yourself only caring about one or the other, having the data separate may make things more efficient.