Braeden Orchard
Braeden Orchard

Reputation: 245

Returning each value from for loop in c#

EDIT: I realized that I had been going about it completely the wrong way and after an overhaul, got it working. Thanks for the tips guys, I'll keep them in mind for the future.

I've hit an unusual problem in my program. What I need to do is find the difference between two times, divide it by 1.5 hours, then return the starting time followed by each 1.5 hour increment of the starting time. So if the time was 11:45 am - 2:45 pm, the time difference is three hours, 3/1.5 = 2, then return 11:45 am and 1:15 pm. At the moment, I can do everything except return more than one time. Depending on what I've tried, it returns either the initial time (11:45 am), the first increment (1:15 pm) or the end time (2:45 pm). So far I've tried a few different types of for and do/while loops. The closest I've come was simply concatenating the start time and the incremented time, but the start and end times can range anywhere from 3 - 6 hours so that's not a practical way to do it.

The latest thing I tried:

int i = 0;
do{
   i++;
   //Start is the starting time, say 11:45 am
   start = start.AddMinutes(90);
   return start.ToShortTimeString();
} while (i < totalSessions); //totalSessions is the result of hours / 1.5

and I'm calling the function on a dynamic label (which is also in a for loop):

z[i] = new Label();
z[i].Location = new Point(PointX, PointZ);
z[i].Name = "sessionTime_" + i;
z[i].Text = getPlayTimes(dt.Rows[i][1].ToString());
tabPage1.Controls.Add(z[i]);
z[i].BringToFront();
PointZ += z[i].Height;

I'm pretty new to c# so I guess I've just misunderstood something somewhere.

Upvotes: 0

Views: 1319

Answers (2)

Monza
Monza

Reputation: 755

I think you're trying to solve the problem the wrong way. Instead of returning each value as you come to it, create a collection ie List, and push each of your results onto the list until your finishing condition is met.

Then, return the whole array as your return value. This way you will have a nice self-contained function that doesn't have cross-concerns with other logic - it does only it's one little task but does it well.

Good luck!

Upvotes: 4

Abion47
Abion47

Reputation: 24726

It's a bit difficult to determine your exact use case, as you haven't offered the complete code you are using. However, you can do what you are asking by using the yield return functionality:

public IEnumerable<string> GetPlayTimes()
{
    int i = 0;
    do
    {
        i++;
        //Start is the starting time, say 11:45 am
        start = start.AddMinutes(90);
        yield return start.ToShortTimeString();
    } while (i < totalSessions); //totalSessions is the result of hours / 1.5
}

And then use it like so:

foreach (var time in GetPlayTimes())
{
    // Do something with time
}

Upvotes: 1

Related Questions