Search code examples
c#arraysexcelstatic-classes

find a value in a nested categorized static class in C#


I need to find a value inside a structure (the first that came in my mind was a static class, but anything will do) that has to be a hierarchical structure like:

public static class SheetGroups
{
    public static class Coverage {
        public static string sheet1 = "COVC1";
        public static string sheet2 = "COVC2";
    }

    public static class IncomeInvestment
    {
        public static string Income1 = "IEIC1";
        public static string Income2 = "IEIC2";
        public static string Income3 = "IEIC3";
        public static string Incomes4 = "IEIC4";
        public static string Investment1 = "IEIC5";
    }
}

The problem with this structure is that I need the groups (Coverage and IncomeInvestment) have values too (like an nested enum), and the other problem is that I have to implement a IfExistString method to find if a String exists within the values assigned.

I've been searching for a solution for a while now, but I cannot find a clean approach for this. For those who were wondering, I need this to validate the correct structure for a Excel file, the root (SheetGroups) stands for a zip file containing a number indetermined of Excel files, the nested clases (Coverage and IncomeInvestment) are Excel Files, then I have Sheets (COVC1, COVC2, etc), then I plan to have one more level, to have columns of tables in every sheet.

Thanks

Omar


Solution

  • I believe that this should be easier to handle if you use dictionary inside dictionary inside dictionary [...] aproach:

    // I'm using collection initializers here! 
    var groups = new Dictionary<string, Dictionary<string, string>>
    {
         { 
              "Coverage", 
              new Dictionary<string, string> 
              {
                   { "sheet1", "COVC1" },
                   { "sheet2", "COVC2" }
                   // And so on...
              }
         },
         {
              "IncomeInvestment",
              new Dictionary<string, string>
              {
                   { "Income1", "IEIC1" }
                   // And so on...
              }
         }
    };
    

    Now you can access values this way:

    string sheet1 = groups["Coverage"]["sheet1"];
    

    ... or you might check if some key exists using out-of-the-box IDictionary<TKey, TValue>.ContainsKey(System.String) method!

    I believe this approach should simplify your task and you can use standard, out-of-the-box dictionary capabilities to search, validate or access its values.