Home > Mobile >  Insert Data from Textfile to List<> with own class in C# WPF
Insert Data from Textfile to List<> with own class in C# WPF

Time:11-10

I have a textfile, that contains lines like: 34;233;1

and

I have a Class with X, Y and i Values called "my_points"

I want to read the file line for line and add a new "my_points" to a List I declared before.

There is no Syntax error but the list is still empty after reading it. I can print out "seperated[0]" , "seperated[1]" or "seperated[2]" and they contain the right numbers from my file. Furthermore the list contoins as many "my_points" as there are lines in my textfile. So this works. But all Values are 0. So I dont understand why the numbers are not in the List.

My Code:

List<my_points> my_point_list_read = new List<my_points>(); //the list is initialized before...

public List<my_points> FiletoList()
        {
            System.IO.StreamReader my_streamreader = new System.IO.StreamReader("Textfile.txt");
            string my_line;
            while ((my_line = my_streamreader.ReadLine()) != null)
            {
                try
                {
                    string[] seperated = my_line.Split(';');
                    my_point_list_read.Add(new my_points(Convert.ToDouble(seperated[0]), Convert.ToDouble(seperated[1]), Convert.ToInt32(seperated[2])));
                    
                }
                catch 
                {
                    break;
                }  
            }
//The class I wrote for my_points looks like this:

public class my_points
        {
            public double X;
            public double Y;
            public int i;
            public my_points(double X, double Y, int i)
            {
                this.X = 0.0;
                this.Y = 0.0;
                this.i = 0;
            }
        }

CodePudding user response:

In my Class my_points I set all the variables to zero. I changed it to:

public class my_points 
{
    public double X;
    public double Y;
    public int i;
    public my_points(double X, double Y, int i)
    {
        this.X = X;
        this.Y = Y;
        this.i = i;
    }
}

And it works now.

CodePudding user response:

I faced this problem once. I solved it using another type of class constructor:

new my_points { X = separated[0], Y = separated[1], i = separated[2] }
  • Related