user4190165
user4190165

Reputation:

Check for the first unfilled Array Element C#

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

Upvotes: 0

Views: 87

Answers (2)

Evgeniy Mironov
Evgeniy Mironov

Reputation: 787

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));

Upvotes: 0

Alexander Pavlenko
Alexander Pavlenko

Reputation: 325

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();
   }
}    

Upvotes: 1

Related Questions