【问题标题】:List to text file列表到文本文件
【发布时间】:2013-02-04 15:04:56
【问题描述】:

我有一个包含一组人的对象列表。每个人都有名字、姓氏、地址和电话号码。

我想将该列表导出到一个文本文件中,如下所示:

A组
名字-大卫
姓氏-kantor
地址-意大利
电话号码-123456

我该怎么办?到目前为止,我设法只导出对象类型名称:

public List<PhoneBookCore> elements = new List<PhoneBookCore>();

string[] lines = elements.Select(phoneBookCore =>
    phoneBookCore.ToString()).ToArray();
System.IO.File.WriteAllLines(path, lines);

【问题讨论】:

  • 你想在这里使用序列化。你可以阅读更多here
  • @darko: 添加PhoneBookCore的结构

标签: c# text-files


【解决方案1】:

您只有对象类型名称,因为PhoneBookCore.ToString() 为您提供对象类型名称。

您必须指定文件的外观。正如 MikeCorcoran 一样,一个很好的方法是使用序列化。这是一种在文件中存储和检索数据的非常强大的方法。

List<string> lines = new List<string>();
foreach(var phoneBookCore in elements)
{
    lines.Add(phoneBookCore.GroupName);  // Adds the Group Name
    foreach(var person in phoneBookCore.Persons)
    {
        // Adds the information on the person
        lines.Add(String.Format("FirstName-{0}", person.FirstName));
        lines.Add(String.Format("LastName-{0}", person.LastName));
        lines.Add(String.Format("Address-{0}", person.Address));
        lines.Add(String.Format("PhoneNumber-{0}", person.PhoneNumber));
    }
}
System.IO.File.WriteAllLines(path,lines);

【讨论】:

    猜你喜欢
    • 2011-03-03
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 2012-03-20
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多