我有以下代码:
public Dictionary<string, BuySellPrices> tauntPrices = new Dictionary<string, BuySellPrices>();
public struct BuySellPrices
{
public int buyPrice;
public int sellPrice;
}
private void TextTauntPriceUpdate()
{
var lines = System.IO.File.ReadLines("tauntprices.txt");
foreach(var line in lines)
{
string[] parts = line.Split('.');
tauntPrices.Clear();
tauntPrices.Add(parts[0], new BuySellPrices {buyPrice = Convert.ToInt32(parts[1]), sellPrice = Convert.ToInt32(parts[2])});
}
}
tauntprices.txt如下所示:
然后我又有了这段代码
TextTauntPriceUpdate();
foreach(var each in tauntPrices)
{
Console.WriteLine(each.Key);
Console.WriteLine(each.Value.buyPrice.ToString());
Console.WriteLine(each.Value.sellPrice.ToString());
}
问题是writeline
只打印出文本文件的最后一行。
另一个问题是,如果我不尝试通过字典打印,但是这样做:
var lines = System.IO.File.ReadLines("tauntprices.txt");
foreach (var line in lines)
{
int bp = 0, sp = 0;
string[] parts = line.Split('.');
int.TryParse(parts[1], out bp);
int.TryParse(parts[2], out sp);
Console.WriteLine(parts[0] + ":" + bp.ToString() + ":" + sp.ToString());
}
完全正常。错误是什么?
答案 0 :(得分:3)
您正在清除文件中每行的字典内容。这就是为什么它最终只能占据最后一行。
tauntPrices.Clear();
foreach(var line in lines)
{
string[] parts = line.Split('.');
....
将.Clear()行移到foreach语句之前:
./app
答案 1 :(得分:2)
因为您每次都使用此语句foreach(var line in lines)
{
string[] parts = line.Split('.');
tauntPrices.Clear(); // ****OOPS!
...