1
var months = 36;

To iterate through the years and have access to each year number (according to how many months I have (above)), I'm currently doing:

var years = Convert.ToInt32(months / 12);

for (int i = 1; i <= years; i++)
{
    var year = 12 * i;
}

However, I'm sure there must be a way of populating a new list of integers as part of a foreach and looping through them (giving me access to the current element rather than recalculating it again inside the for loop). I'm looking for help writing that foreach. Possibly a LINQ .Select()? I really don't like this current approach.

Desired Result

foreach(var year in new List<int>(){ 1, 2, 3})
{
}
Habib
  • 219,104
  • 29
  • 407
  • 436
  • A downvote's great if it's accompanied with an explanation. Where have I gone wrong? –  Sep 10 '14 at 15:07
  • slightly off topic, but you can do `var years = months / 12`, there is no need to `Convert.Int32`, both of your operands `months` and `12` are integer values and would produce an `int` output. – Habib Sep 10 '14 at 15:28
  • @Habib - thanks again. Rather basic question, but what if it were `4 / 3`? –  Sep 10 '14 at 15:31
  • it would be `1`, since the division is done for int values the result would be integer. similarly for `3 / 4`, the result would be `0` – Habib Sep 10 '14 at 16:05
  • 1
    Also see http://stackoverflow.com/questions/1205490/why-do-these-division-equations-result-in-zero – Habib Sep 10 '14 at 16:07

1 Answers1

6

Something like this?:

foreach (var year in Enumerable.Range(1, months / 12))
David
  • 208,112
  • 36
  • 198
  • 279
  • Exactly like that, yes. Brilliant. Thanks mate. –  Sep 10 '14 at 15:06
  • 2
    +1, if Month value is `37` and the OP needs 4 years for it then `Enumerable.Range(1, (int) Math.Ceiling(month / 12d))` – Habib Sep 10 '14 at 15:07
  • @Habib - thanks. Valid point. I'm safe from that for now, but it's worth me including it just to be more defensive. –  Sep 10 '14 at 15:08
  • 1
    @Habib: True, there are a number of logical considerations to be made in this calculation. Depending on what behavior the OP is looking for. – David Sep 10 '14 at 15:08