Lukas Velička
Lukas Velička

Reputation: 37

c# How to to remove line in array?

My method looks like this:

void OldOnesToFile(List<Student> students)
{
    string[] lines = new string[students.Count];

    int i = 0;

    foreach (Student student in students)
    {
        if (student.Course > 1)
            lines[i] = String.Format(
               "{0} {1} {2} {3} {4} {5} {6}", 
                students[i].LastName, 
                students[i].FirstName, 
                students[i].Birthday, 
                students[i].StudId, 
                students[i].Course, 
                students[i].MobileNumber, 
                students[i].Freshman);
            else 
                lines[i] = remove //Something like that??

            i++;
        }

        File.WriteAllLines(@"senbuviai.txt", lines);
    }

Take a look where I've left a comment. How should I write code that if a student's course is not bigger than 1, that line would delete or would disappear because I got something like that.

enter image description here

Upvotes: 0

Views: 1566

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Why using array at all? List<string> is by far more convenient:

void OldOnesToFile(List<Student> students)
{
    List<string> lines = new List<string>();

    foreach (Student student in students)
    {
        if (student.Course > 1)
            lines.Add(String.Format(...));
    }

    File.WriteAllLines(@"senbuviai.txt", lines);
}

or even Linq:

 void OldOnesToFile(List<Student> students)
 {
     File.WriteAllLines(@"senbuviai.txt", students
       .Where(student => student.Course > 1)
       .Select(student => string.Format(...)));  
 } 

Upvotes: 8

Related Questions