I am an experienced PHP developer moving to C #. I am currently working on a Windows Forms application.
In my searches, I found that C # does not support associative arrays in the same way as PHP. I found information about the dictionary and something about the "structures" that appear to be class objects.
I'm having a problem not only with an associative array, but also with a multidimensional one, which I want to use to store several counters in a series of loops.
The application reads a text log file, looks for a predetermined line, draws a date in this line when a line is detected, and increments the counter for this line in that date.
In PHP, it would be so simple:
// Initialize $count_array[$string_date][$string_keyword] = 0; ... // if string is found $count_array[$string_date][$string_keyword] += 1; ... // To ouput contents of array foreach($count_array as $date -> $keyword_count_array) { echo $date; // output date foreach($keyword_count_array as $keyword -> $count) { echo $keyword . ": " . $count; } }
It seems to be a bit more involved in C # (which is not so bad). I tried using a sentence that I found on another similar question, but I really do not follow how to either increase or iterate / output the content:
// Initialize var count_array = new Dictionary<string, Dictionary<string, int>>(); count_array = null; ... // if string is found - I think the second reference is supposed to be a Dictionary object?? count_array[string_date.ToShortDateString()][string_keyword]++; ... // To ouput contents of "array" foreach (KeyValuePair<string, Dictionary<string, int>> kvp in exportArray) { foreach(KeyValuePair<string, int> kvp2 in kvp.Value) { MessageBox.Show(kvp.Key + " - " + kvp2.Key + " = " + kvp2.Value); } }
Am I even on the right track? Or does anyone have a better / cleaner method of spoofing PHP code above?
UPDATE
With the above C # code, I really get an error message in the string "// if string found". Error: "The object reference is not installed on the object instance." I assume this is because I have a line in a reference article, not in a dictionary. So right now I'm not sure how to grow.
UPDATE 2
Thank you all for your time. The current code now functions thanks to an understanding of how the dictionary works. However, all advice regarding the use of classes and objects for this situation is also not lost. I can reorganize to satisfy.