In my app I am writing data into a text file by converting a list into an array, later on I want to load it by converting it to the same list type and return it like that.
My code:
public abstract class PhoneBookCore
{
protected string _group;
public PhoneBookCore(string group)
{
this._group = group;
}
}
public class Group : PhoneBookCore
{
private List<PhoneBookCore> elements = new List<PhoneBookCore>();
public List<PhoneBookCore> elementsList {
get { return new List<PhoneBookCore>(elements); }
}
public Group(string name)
: base(name)
{
}
class DataOptions
{
public void Save(Group g)
{
string[] lines = g.elementsList.ConvertAll(p => p.ToString()).ToArray();
File.WriteAllLines(path, lines);
}
public Group Load()
{
string[] buffer = File.ReadAllLines(path); // ----> How do I convert it back
// to list of type group?
return ;
}
}
How do I convert it back to list of type group?
Maybe (assuming that you want to pass the whole line to the Group-constructor)
Note that I’ve used
File.ReadLineswhich returns a streamingIEnumerable<string>instead of astring[], you can also read all into memory at once withFile.ReadAllLines.But why do you always create a new list in the
elementsListproperty? Just returnelements.Edit If you want to create one group and set the
elementsListfrom the lines, you need to provide the setter of the property first:Then you can initialize and set the group on this way: