0

I have a class called cEspecie like this

public class cEspecie
{
    private string name;
    private int lifetime;
    private int movility;
    private int deadto;
    private int type;

public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name= value;
        }
    }
public int Type
    {
        get
        {
            return type;
        }
        set
        {
            type = value;
        }
    }
public int LifeTime
    {
        get
        {
            return lifetime;
        }
        set
        {
            lifetime= value;
        }
    }
public int Movility
    {
        get
        {
            return movility;
        }
        set
        {
            movility = value;
        }
    }
public int DeadTo
    {
        get
        {
            return deadto;
        }
        set
        {
            deadto = value;
        }
    }
}

I store some data in a list called

List<cEspecie> list = new List<cEspecie>() { 
new cEspecie("Wolf", 100, 10, 0, 0)
new cEspecie("Rabiit", 100, 100, 1, 1), 
new cEspecie("Lion", 200, 10, 2, 2), 
new cEspecie("Tiger", 300, 10, 3, 3),  
};

In one of the process of my program i store all the data inside a text file using this:

using (StreamWriter sr = new StreamWriter(@"../../Archives/TextFilecEspecie.txt"))
        {
            foreach (var item in list)
            {   
                sr.WriteLine(item.Name);
                sr.WriteLine(item.Type);
                sr.WriteLine(item.Movility);
                sr.WriteLine(item.LifeTime);
                sr.WriteLine(item.DeadTo);
            }
            sr.Close();
        }

the result inside "TextFilecEspecie.txt" was this:

Wolf
100
10
0
0
Rabiit
100
100
1
1
Lion
200
10
2
2
Tiger
300
10
3
3

now my real, real problem is ... How can i get back the same data to store it in the same list? I'm using c# and wpf and i really dont find an answer.

user3023107
  • 19
  • 2
  • 5
  • 3
    `Movility` sounds cool. – canon Nov 22 '13 at 20:05
  • What have you tried? What don't you understand? Are you asking how to read a line from a text file? How to convert a string to a number? How to loop through the file? – SLaks Nov 22 '13 at 20:06
  • Actually due to the properties of the class, I dont know how to assign them to each one while reading the text file. – user3023107 Nov 22 '13 at 20:08
  • 1
    Maybe you should have delimited the objects to one line then you read each line and `Split` the line on the delimiting char and rebuild your objects. – OneFineDay Nov 22 '13 at 20:08
  • 1
    as a sidenote calling sr.Close() is not necessary and should be avoided if you use the using statement – Fabio Marcolini Nov 22 '13 at 20:22

6 Answers6

5

Using LINQ, and the Buffer extension method from Microsoft's excellent Ix-Main package.

var species = File.ReadLines("file.txt")
                .Buffer(5)
                .Select(x => new cEspecie
                {
                    Name = x[0],
                    Type = int.Parse(x[1]),
                    Movility = int.Parse(x[2]),
                    LifeTime = int.Parse(x[3]),
                    DeadTo = int.Parse(x[4])
                });

Buffer(5) will group every 5 lines into an array.

Cory Nelson
  • 29,236
  • 5
  • 72
  • 110
  • Instead of Buffer, you can use implementation from the answer: http://stackoverflow.com/questions/419019/split-list-into-sublists-with-linq – Dariusz Woźniak Nov 22 '13 at 20:36
2

This is what serialization and ISerializable are for.

Here is a quick tutorial that should make it fairly simple.

I might even recommend JSON.Net, which will write it in JSON format so you could more easily create/edit the objects in the file.

Community
  • 1
  • 1
Erik Kerber
  • 5,646
  • 7
  • 38
  • 56
1

You do the same thing only backwards using StreamReader to read the file. I won't get into specifics since I'm guessing you can use the learning experience so consider this a point to the right direction and homework :)

System Down
  • 6,192
  • 1
  • 30
  • 34
0

you can do that this way

        var list = new List<cEspecie>();
        using (StreamReader reader = File.OpenText(filePath))
        {
            while(!reader.EndOfStream)
            {
                string name = reader.ReadLine();
                int type = int.Parse(reader.ReadLine());
                int movility = int.Parse(reader.ReadLine());
                int lifeTime = int.Parse(reader.ReadLine());
                int deadTo = int.Parse(reader.ReadLine());
                list.Add(new cEspecie(name, type, movility, lifeTime, deadTo));
            }
        }

note that:

  1. int.Parse throw error if the string is not a int, use TryParse the data may not be a int
  2. this work only if the file has the correct number of lines
Fabio Marcolini
  • 2,315
  • 2
  • 24
  • 30
0
var list = File.ReadLines("path").Select(x => new cEspecie(x));

in cEspecie constructor you can initialize the object using input line.

Mayank
  • 8,777
  • 4
  • 35
  • 60
  • 1
    @FabioMarcolini This gives you a `List` not a list `List`... It's the cleanest way to read the file but is far from solving the problem. Also, give the format of the input this isn't a usable solution. If each object was like comma delimited on a single line you could use `ReadAllLines` then do `Select(x => x.Split(',')` then pass the tokens into a constructor and make alist of objects but the way he's readying the ifle doesn't allow for that. – evanmcdonnal Nov 22 '13 at 20:12
0

Something like this is very simple and should work. Do error checking though.

List<cEspecie> list = new List<Persona>();  
string[] readText = File.ReadAllLines(@"../../Archives/TextFilecEspecie.txt");

for(int i=0;i<readText.Length/5;i++)
{
    list.Add(new Persona(readText[i*5], readText[i*5+1], readText[i*5+2], readText[i*5+3], readText[i*5+4]));
}
AwokeKnowing
  • 7,728
  • 9
  • 36
  • 47