0

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

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

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

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

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

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

1 回答 1

4

您只有对象类型名称,因为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);
于 2013-02-04T15:20:36.973 回答