将字典内容保存到文件

时间:2013-10-10 20:23:37

标签: c# list dictionary

我正在尝试使用列表和计算唯一实例来执行非常具体的操作,然后将其保存在文件的新行中。

基本上,我有一组包含一组列的列表视图,我想遍历整个列表,并保存每个唯一项的计数。

示例,像这样的列表;

111
222
111
333
333
333

最终将被写入文件:

111:2
222:1
333:3

我不需要它以任何特定的顺序,只要我有这些值。

到目前为止,我有这个;

string fileName = Application.StartupPath + @"\txn_" + 
    TerminalConfig.CreateSafSig() + ".saf";

Dictionary<string, int> products = new Dictionary<string, int>();
List<string> codes = new List<string>();

foreach (ListViewItem item in BasketList.Items)
{ 
    codes.Add(item.SubItems[3].Text); 
}

String[] items = codes.ToArray();
foreach (String code in items)
{
    if (products.ContainsKey(code) != true)
    { 
        products.Add(code, 1); 
    }
    else 
    { 
        products[code] += 1; 
    }
}

foreach (var entry in products)
{ 
    File.WriteAllText(fileName, string.Format("{0}:{1}",entry.Key,entry.Value)); 
}

但它保存的文件只给了我最后一行。 在上面的示例中,它只会显示333:3

我很确定我写得正确,而且我很难找到我出错的地方。

4 个答案:

答案 0 :(得分:4)

File.WriteAllText写一个新文件。每次迭代for循环时都会覆盖文件,只给出最后一行。

msdn页面显示

  

创建新文件,将内容写入文件,然后关闭   文件。如果目标文件已存在,则会被覆盖。

您可以将File.WriteAllText替换为File.AppendAllText,其中包含:

  

打开文件,将指定的字符串附加到文件中,然后   关闭文件。如果该文件不存在,则此方法创建一个   file,将指定的字符串写入文件,然后关闭文件。

如果您想一次性写入文件,可以使用File.WriteAllLines(string path,IEnumerable<string> contents);哪个

  

创建一个新文件,将一组字符串写入该文件,然后   然后关闭文件。

在您的情况下替换:

foreach (var entry in products)
{ 
    File.WriteAllText(fileName, string.Format("{0}:{1}",entry.Key,entry.Value)); 
}

var entries = from entry in products select string.Format("{0}:{1}",entry.Key,entry.Value);
File.WriteAllLines(fileName,entries);

答案 1 :(得分:2)

问题是你在循环的每次迭代时都会覆盖文件。

代码修复:

StringBuilder str = new StringBuilder();


foreach (var entry in products)
{
   str.AppendLine(string.Format("{0}:{1}", entry.Key, entry.Value));
}
File.WriteAllText(fileName, str.ToString()); }

在这里跳转linq的潮流是制作字典的代码:

Dictionary<string, int> products = 
    BasketList.Items.GroupBy(element => element.SubItems[3].Text)
                    .ToDictionary(k => k.Key, c => c.Count())

是的,在linq中将所有这些行替换为一行。

答案 2 :(得分:2)

Harrison回答了为什么你的代码无法运行...现在让我告诉你为什么Jonesy(粗鲁地)建议你使用GroupBy ......

File.WriteAllLines(fileName,
               from item in BasketList.Items
               group item by item.SubItems[3].Text into grp
               select string.Format("{0}:{1}", grp.Key, grp.Count()));

这有效地取代了您的所有代码。 效率较低 - GroupBy在您真正只需要计数时创建项目组,因此它在内存使用方面有点重量级 - 但这通常不是很大重要因素。关于简洁,有一些话要说。

答案 3 :(得分:0)

WriteAllText函数将使用您提供的字符串覆盖文件内容。您应该使用AppendAllText函数

相关问题