我正在尝试根据某些条件确定字典中的值。应用程序必须循环遍历每一行,并且一旦满足某个条件,则必须将值添加到字典中。以下是循环执行并确定要添加的值的任务代码。
foreach (var line in this.FileLines)
{
count++;
string[] bits = line.Split(',');
fineNumber = bits[0].Trim();
int length = bits.Length;
if (length == 9)
{
//other processing gets done here, code not included as its of no interest for this question
}
else
{
//AddErrorFinesToFile(line, fineNumber);
AddFinesToDictonary(fineNumber, line);
continue;
}
}
然后下面是实际的方法签名及其代码,在这个方法中,我只是尝试在字典中添加值。
public Dictionary<string, string> AddFinesToDictonary(string fineNumber, string errorLine)
{
Dictionary<string, string> erroredLines = new Dictionary<string, string>();
erroredLines.Add(fineNumber, errorLine);
return erroredLines;
}
这里似乎唯一出现的问题是,只有最新的值被添加到字典中,这意味着之前的附加值会被覆盖。
答案 0 :(得分:2)
将erroredLines作为全局范围。
Dictionary<string, string> erroredLines = new Dictionary<string, string>();
foreach (var line in this.FileLines)
{
count++;
string[] bits = line.Split(',');
fineNumber = bits[0].Trim();
int length = bits.Length;
if (length == 9)
{
//other processing gets done here, code not included as its of no interest for this question
}
else
{
//AddErrorFinesToFile(line, fineNumber);
AddFinesToDictonary(fineNumber, line);
continue;
}
}
public void AddFinesToDictonary(string fineNumber, string errorLine)
{
erroredLines.Add(fineNumber, errorLine);
// return erroredLines;
}
也无需返回erroredLines字典。
答案 1 :(得分:1)
这个怎么样;
Dictionary<string, string> erroredLines = new Dictionary<string, string>();
foreach (var line in this.FileLines)
{
count++;
string[] bits = line.Split(',');
fineNumber = bits[0].Trim();
int length = bits.Length;
if (length == 9)
{
//other processing gets done here, code not included as its of no interest for this question
}
else
{
erroredLines.Add(fineNumber, line);
continue;
}
}
在foreach之后你可以使用erroredLines字典。
答案 2 :(得分:0)
原因是每次向目录添加数据时都会创建一个新数据,而不是将数据添加到现有数据
您可以做出两种选择:
out
引用传递给函数@Hameed Syed的回答已经给出了第一个(选项1)。
以下是如何将Dictionary作为ref参数(out
)传递给函数(选项2):
public void AddFinesToDictonary(out Dictionary<string,string>dict, string fineNumber, string errorLine)
{
dict.Add(fineNumber, errorLine);
}