0

I'm currently developing a Console App to manage students. I have the Classes and Methods all set up and they are accesible. However, When I'm editing the "add" method, I use a for loop to create a INTEGER that contains the Array Element that contains "".

I use

for (int i = 0; p.students[i] != ""; i++)
{
    Console.WriteLine(i);
    Console.ReadKey();
}

Its supposed to start at ZERO and if the Array Element of the value of i = "".... it adds 1 to i and starts again. However it seems to stop at 0. I know that the first 3 elements have content while the 4th is "".

Any idea what I'm doing wrong?

Thanks in advance, Bryan

4
  • If the array hold student objects, none are likely to be "". Use a List<Student> to obviate the issue - they never have empty elements. Commented Nov 27, 2014 at 22:25
  • How do you fill p.students and what do you mean with "seems to stop"? Commented Nov 27, 2014 at 22:26
  • Can you please make a mcve with actual and expected output? It is difficult to tell what you are trying to do. Commented Nov 27, 2014 at 22:26
  • @Plutonix I have the 4th and final element containing "" Commented Nov 27, 2014 at 22:28

2 Answers 2

1

First of all using expression

p.students[i] != ""

as loop condition is a really bad practice.

You could make it with the following code:

for (var i = 0; i < p.students.Lenght; i++)
{
   if(p.students[i] == string.Empty)
   { 
      Console.WriteLine(i);
      Console.ReadKey();
   }
}    
Sign up to request clarification or add additional context in comments.

Comments

0

With LINQ:

p.students.Select((s, i) => new { Student = s, Num = i })
          .Where(e => e.Student == string.Empty)
          .ToList().ForEach(e => Console.WriteLine(e.Num));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.