现在我有一个字典,其中填充了一个帐户作为键,一个列表作为值。我相信我的代码正在努力填充它。但我的下一步是迭代与特定键关联的列表,并对列表进行操作(获取每个字段的总和)。我对字典不太熟悉,所以我不确定如何访问这些值并执行操作。当我退出 while 循环时,我想进行此求和并在 for every 循环中将其打印出来。
1)如果我能弄清楚如何访问 DataRecords 中的每个字段(在 foreach 循环内),我可能就能弄清楚如何进行求和。
2)还寻找一种打印值的方法,以便我可以查看它是否正确填充。
static void Main(string[] args)
{
Dictionary<string, List<DataRecord>> vSummaryResults = new Dictionary<string, List<DataRecord>>();
while (!r.EndOfStream)
{
if (control == "1")
{
// Need to add List<Datarecords> into dictionary...
if (vSummaryResults.ContainsKey(records.account))
{
vSummaryResults[records.account].Add(records);
}
else
{
vSummaryResults.Add(records.account, new List<DataRecord>());
vSummaryResults[records.account].Add(records);
}
}
}
foreach (List<DataRecord> rec in vSummaryResults.Values)
{
Console.WriteLine(rec.); dictionary.
}
vWriteFile.Close();
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
这是DataRecord我用作列表中对象的类。
公共类 DataRecord { 字段..... }
对于字典的迭代,我们使用KeyValuePair:
foreach (KeyValuePair<string, List<DataRecord>> kvp in vSummaryResults)
{
string key = kvp.Key;
List<DataRecord> list = kvp.Value;
Console.WriteLine("Key = {0}, contains {1} values:", key, list.Count);
foreach (DataRecord rec in list)
{
Console.WriteLine(" - Value = {0}", rec.ToString()); // or whatever you do to put list value on the output
}
}
Run Code Online (Sandbox Code Playgroud)