Ghasem
Ghasem

Reputation: 15563

Check if "for loop" is in first or last iteration in C#

I have a for loop in my list which I want to do something different with the first and the last iterations. I found this question which is about foreach loop. How Can I do achieve purpose in a for loop ?

string str;
for (int i = 0; i < myList.Count; i++)
{
     //Do somthin with the first iteration
     str = "/" + i;
     //Do somthin with the last iteration
}

I want to know if there's an other way than this:

for (int i = 0; i < myList.Count; i++)
{
    if (i == 0)
    {
        //Do somthin with the first iteration
    }
    str = "/" + i;
    if (i == myList.Count-1)
    {
        //Do somthin with the last iteration
    }
}

Upvotes: 0

Views: 3751

Answers (3)

furkle
furkle

Reputation: 5059

If you wanted to entirely avoid conditionals in your for loop (and that's what it seems like based on the details you've provided), you should just execute whatever logic you like on the first and the last items. Then, you can structure your for loop so that it ignores the first and last elements in the enumerable (initialize i as 1 and change your condition to i < myList.Count - 1).

if (myList != null && myList.Count >= 2)
{
    YourFirstFunction(myList[0]);

    for (int i = 1; i < myList.Count - 1; i++)
    {
        YourSecondFunction(myList[i])
    }

    YourThirdFunction(myList[myList.Count - 1]);
}

Replace YourNFunction with whatever logic you'd like to apply to the first index, the between indices, and the last index, respectively.

Note that I've checked whether myList has two or more items - I don't think this logic makes any sense unless, at the very least, the first and the last indices aren't the same. Given that you also plan to do something with items in-between, you might want to change it to 3, so as to ensure that you've always got a distinct beginning, middle, and end.

Upvotes: 2

Rufus L
Rufus L

Reputation: 37020

Just do something with the first and last items, and then loop through the rest:

if (myList != null && myList.Any())
{
    // Do something with the first item here  
    var str = "** START **" + myList.First();

    for (int i = 1; i < myList.Count - 1; i++)
    {
        str += "/" + i;
    }

    //Do something with the last item here 
    if (myList.Count > 1) str += myList.Last() + " ** END **";
}

Upvotes: 1

danish
danish

Reputation: 5600

You can start the loop at 1 and do first iteration processing outside. Something like this:

if(myList != null && myList.Count > 0){
// Process first and last element here using myList[0] and myList[myList.Count -1]

}

for(int i = 1; i <myList.Count - 1;i++){
// process the rest
}

You will need to consider scenario where myList has only one element.

Upvotes: 1

Related Questions