Reputation: 875
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
Upvotes: 0
Views: 101
Reputation: 28338
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:
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.
public class Category
{
public int Id;
public string Name;
Dictionary<int, string> Subcategories = new Dictionary<int, string>();
}
Dictionary<int, Category> Categories;
(I'd also consider a KeyedCollection
here that can extract the Id
from a Category
as the key directly.)
The downside: its a bit more work to add or retrieve a subcategory because you have to do two lookups:
var subcategory = Categories[1].Subcategories[1];
If your data structure rarely changes you can use a 4-field Tuple<>
:
List<Tuple<int, int, string, string>> Categories;
var subcategory = Categories.Where(x => Item1 == 1 && Item2 == 1);
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):
Dictionary<Tuple<int, int>, Tuple<string, string>> Categories;
But IMO that gets kinda messy, and at that point I'd just go with a custom class.
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:
Dictionary<id, string> CategoryNames;
Dictionary<id, Dictionary<id, string>> Subcatgories;
This is more flexible than the Tuple
solution 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.
Upvotes: 2
Reputation: 4501
You can use Dictionary also as the value of the main dictionary. So you would access your data using dict[category][sub]
Another option is to use Tuple as they key which "codes" both the main key, and the secondary key into a single unique key
Upvotes: 0