C#4.0 - 多维关联数组(或模仿一个?)

Aar*_*ryn 6 .net c# associative-array multidimensional-array

我是一位经验丰富的PHP开发人员,过渡到C#.目前我正在开发Windows窗体应用程序.

我在搜索中发现C#不像PHP那样以松散的方式支持关联数组.我在Dictionary上找到了关于"结构"的信息,它们似乎是类对象.

我遇到的麻烦不仅是关联数组,而是一个多维数组,我想用它来保持一系列循环中的多个计数.

应用程序正在读取文本日志文件,搜索预定义的字符串,在找到该字符串时拉出该行上的日期,并在该日期递增该字符串匹配的计数.

在PHP中,它会像这样简单:

// 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

它似乎更多地涉及C#(这不是一件坏事).我试过使用我在另一个类似问题上找到的建议,但我并没有真正遵循如何增加或迭代/输出内容:

// 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我是否走在正确的轨道上?或者有人有更好/更清洁的方法来模仿上面的PHP代码?

UPDATE

使用上面的C#代码,我实际上在"// if string is found"行中收到错误.错误是"对象引用未设置为对象的实例".我假设这是因为我在secound引用中有一个字符串,而不是Dictionary对象.所以现在,我不确定如何增加.

更新2

谢谢大家的时间.由于理解了Dictionary的工作方式,当前的代码现在可以正常运行.但是,对于这种情况使用类和对象的所有建议也不会丢失.我可以重构以适应.

McA*_*den 4

代码本身看起来不错,我认为唯一缺少的是在增加值之前没有检查这些值是否存在。

在您致电之前

count_array[string_date.ToShortDateString()][string_keyword]++;
Run Code Online (Sandbox Code Playgroud)

你需要做:

string shortDate = string_date.ToShortDateString();
if (!count_array.ContainsKey(shortDate))
{
    count_array.Add(shortDate, new Dictionary<string, int>());
}

if (!count_array[shortDate].ContainsKey(string_keyword))
{
    count_array[shortDate].Add(string_keyword, 0);
}
Run Code Online (Sandbox Code Playgroud)

在尝试增加任何东西之前。

您需要通过调用 .Add 或 ["key"] = value 来初始化字典条目。对未初始化的字典条目调用 ++ 不起作用。尽管使用类可能是一个好主意,但这取决于您想要完成的具体任务。