473,320 Members | 1,535 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Last row in foreach loop

Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?

foreach (Racecar racecar in RaceCarCollection)
{
...

if last row do something?
}

You can tell how many items you have in the collection but is there way to
tell which row you are looking or if this is the last row?

Thanks,

Tom
Feb 29 '08 #1
23 29906
tshad skrev:
Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?

foreach (Racecar racecar in RaceCarCollection)
{
...

if last row do something?
}

You can tell how many items you have in the collection but is there way to
tell which row you are looking or if this is the last row?
Not without counying an test against RaceCarCollection.Count (or .Length)

Why not use a for loop instead?
--
Bjørn Brox
Feb 29 '08 #2
On Feb 29, 4:02*pm, "tshad" <ts...@dslextreme.comwrote:
Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?

foreach (Racecar racecar in RaceCarCollection)
{
* * ...

* * if last row do something?

}

You can tell how many items you have in the collection but is there way to
tell which row you are looking or if this is the last row?

Thanks,

Tom
Not as far as I am aware of. I have done someting like this with:

foreach (int i = 0; i < collection.Count; i++)
{
object = collection[i];
...
if (i == collection.Count - 1)
do something to the last object
}
Feb 29 '08 #3
Doubt it. I've always use a counter variable and compared to the length of
the collection. Not a big deal.
-- Peter
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
Short Urls & more: http://ittyurl.net
"tshad" wrote:
Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?

foreach (Racecar racecar in RaceCarCollection)
{
...

if last row do something?
}

You can tell how many items you have in the collection but is there way to
tell which row you are looking or if this is the last row?

Thanks,

Tom
Feb 29 '08 #4
Besides what others have mentioned, here is another way to tackle your
problem without having to have a counter in case you had something against
counters.
Racecar lastRacecar;
foreach (Racecar racecar in RaceCarCollection)
{
lastRacecar = racecar;

// Do something...........
}
if(lastRacecar != null)
{
// Do last row stuff here...........
}

"tshad" <ts***@dslextreme.comwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?

foreach (Racecar racecar in RaceCarCollection)
{
...

if last row do something?
}

You can tell how many items you have in the collection but is there way to
tell which row you are looking or if this is the last row?

Thanks,

Tom

Feb 29 '08 #5
On 29 Feb, 22:02, "tshad" <ts...@dslextreme.comwrote:
Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?

foreach (Racecar racecar in RaceCarCollection)
{
* * ...

* * if last row do something?

}

You can tell how many items you have in the collection but is there way to
tell which row you are looking or if this is the last row?

Thanks,

Tom
Sounds like you should test doing that with a database, the price for
MySQL or if you want to go M$ SQLserverExpress is nice (0$), a
pseudostatement like "readline(); if next line is EOF..." is not too
hard to program logically but you get double the IO, and for
nothing.. or as mentioned check the length..
//CY
Feb 29 '08 #6
On Feb 29, 4:17*pm, za...@construction-imaging.com wrote:
On Feb 29, 4:02*pm, "tshad" <ts...@dslextreme.comwrote:


Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?
foreach (Racecar racecar in RaceCarCollection)
{
* * ...
* * if last row do something?
}
You can tell how many items you have in the collection but is there way to
tell which row you are looking or if this is the last row?
Thanks,
Tom

Not as far as I am aware of. I have done someting like this with:

foreach (int i = 0; i < collection.Count; i++)
{
* * object = collection[i];
* * ...
* * if (i == collection.Count - 1)
* * * * do something to the last object

}
Sorry, that should be for instead of foreach.
Feb 29 '08 #7

You can get the enumerator then use Reset, Current, & MoveNext but it's ugly.

IEnumerator<RaceCare = RaceCarCollection.GetEnumerator();
e.Reset();
bool isValid = e.MoveNext();
while (isValid)
{
RaceCar car = e.Current;
isValid = e.MoveNext();
if ( !isValid )
{
// this is the last car
}
}
tshad wrote:
Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?

foreach (Racecar racecar in RaceCarCollection)
{
...

if last row do something?
}

You can tell how many items you have in the collection but is there way to
tell which row you are looking or if this is the last row?

Thanks,

Tom

Feb 29 '08 #8


"tshad" wrote:
Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?

foreach (Racecar racecar in RaceCarCollection)
{
...

if last row do something?
}

You can tell how many items you have in the collection but is there way to
tell which row you are looking or if this is the last row?

Thanks,

Tom
Won't the following work? I can't say it's efficient...

if (racecar == RaceCarCollection [RaceCarCollection.count - 1])
{
// do something...
}
>
Mar 1 '08 #9
On Mar 1, 1:50 am, Family Tree Mike
<FamilyTreeM...@discussions.microsoft.comwrote:
Won't the following work? I can't say it's efficient...

if (racecar == RaceCarCollection [RaceCarCollection.count - 1])
{
// do something...

}
That entirely depends on the type of RaceCarCollection. If it's just
an IEnumerable<T>, it doesn't have a Count property.

Jon
Mar 1 '08 #10
Jon Skeet [C# MVP] wrote:
tshad <ts***@dslextreme.comwrote:
>Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?
There is using "SmartEnumerable" from my (free) MiscUtil library:

http://pobox.com/~skeet/csharp/miscu...numerable.html
Nice :)
'When C# 3 is released, this pattern will be made even simpler with'

Any chance for that update ? :-)

See ya
Søren Reinke
Mar 1 '08 #11
What occurs to me is that you only want something done once, so why put it
in the loop at all?

foreach (RaceCar currentRaceCar in RaceCarCollection)
currentRaceCar.Start();

RaceCarCollection[RaceCarCollection.Count - 1].BreakDown();


Mar 1 '08 #12
Jon Skeet [C# MVP] wrote:
Søren Reinke <so***@REMOVE.reinke.dkwrote:
>>http://pobox.com/~skeet/csharp/miscu...numerable.html
Nice :)
'When C# 3 is released, this pattern will be made even simpler with'

Any chance for that update ? :-)
The implicit typing is something I don't need to do anything with, but
I'll put in the extension method when I get a bit of time - thanks for
the reminder :)
:-)

No problem.

I just enjoy getting tips from your website :-)

See ya
Søren Reinke
Mar 1 '08 #13


"Jon Skeet [C# MVP]" wrote:
On Mar 1, 1:50 am, Family Tree Mike
<FamilyTreeM...@discussions.microsoft.comwrote:
Won't the following work? I can't say it's efficient...

if (racecar == RaceCarCollection [RaceCarCollection.count - 1])
{
// do something...

}

That entirely depends on the type of RaceCarCollection. If it's just
an IEnumerable<T>, it doesn't have a Count property.

Jon
I see your point in earlier versions, but under 2008, IEnumerable<T>
supports a Count() method, but not a property. The original poster said they
knew the count though.
Mar 1 '08 #14
"Bjørn Brox" <bp****@gmail.comwrote in message
news:47********@news.broadpark.no...
tshad skrev:
>Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?

foreach (Racecar racecar in RaceCarCollection)
{
...

if last row do something?
}

You can tell how many items you have in the collection but is there way
to tell which row you are looking or if this is the last row?
Not without counying an test against RaceCarCollection.Count (or .Length)

Why not use a for loop instead?
I could.

But it wasn't a problem just a question.

At the moment, I just set iktr= 0 and just a line after the foreach line
(iktr++;) and then test against RaceCarCollection.Count as you mentioned.

I was just curious if there was a property somewhere that told you what line
in the collection you were on without having to do this.

Thanks,

Tom
>

--
Bjørn Brox

Mar 2 '08 #15

<za***@construction-imaging.comwrote in message
news:d5**********************************@e6g2000p rf.googlegroups.com...
On Feb 29, 4:02 pm, "tshad" <ts...@dslextreme.comwrote:
Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?

foreach (Racecar racecar in RaceCarCollection)
{
...

if last row do something?

}

You can tell how many items you have in the collection but is there way to
tell which row you are looking or if this is the last row?

Thanks,

Tom

Not as far as I am aware of. I have done someting like this with:
>foreach (int i = 0; i < collection.Count; i++)
{
object = collection[i];
...
if (i == collection.Count - 1)
do something to the last object
}
Something like this is fine but I might just as well do:

int iKtr = 0;
foreach (Racecar racecar in RaceCarCollection)
{
iKtr++;
...

if( iKtr == RaceCarCollection.Count)
do something?
}

Thanks,

Tom
Mar 2 '08 #16

"Peter Bromberg [C# MVP]" <pb*******@yahoo.NoSpamMaam.comwrote in message
news:B2**********************************@microsof t.com...
Doubt it. I've always use a counter variable and compared to the length of
the collection. Not a big deal.
I do the same. And as you said, no big deal.

I was just curious if there was a better way.

Thanks,

Tom
-- Peter
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
Short Urls & more: http://ittyurl.net
"tshad" wrote:
>Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?

foreach (Racecar racecar in RaceCarCollection)
{
...

if last row do something?
}

You can tell how many items you have in the collection but is there way
to
tell which row you are looking or if this is the last row?

Thanks,

Tom

Mar 2 '08 #17

"Rene" <a@b.comwrote in message
news:uC**************@TK2MSFTNGP04.phx.gbl...
Besides what others have mentioned, here is another way to tackle your
problem without having to have a counter in case you had something against
counters.
Racecar lastRacecar;
foreach (Racecar racecar in RaceCarCollection)
{
lastRacecar = racecar;

// Do something...........
}
if(lastRacecar != null)
{
// Do last row stuff here...........
}
Huh?

How would racecar ever be null?

lastRaceCar would always be equal to the current row.

Tom
"tshad" <ts***@dslextreme.comwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
>Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?

foreach (Racecar racecar in RaceCarCollection)
{
...

if last row do something?
}

You can tell how many items you have in the collection but is there way
to tell which row you are looking or if this is the last row?

Thanks,

Tom


Mar 2 '08 #18

"Family Tree Mike" <Fa************@discussions.microsoft.comwrote in
message news:97**********************************@microsof t.com...
>

"tshad" wrote:
>Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?

foreach (Racecar racecar in RaceCarCollection)
{
...

if last row do something?
}

You can tell how many items you have in the collection but is there way
to
tell which row you are looking or if this is the last row?

Thanks,

Tom

Won't the following work? I can't say it's efficient...

if (racecar == RaceCarCollection [RaceCarCollection.count - 1])
{
// do something...
}
Actually, that might work.

Thanks,

Tom
>
>>

Mar 2 '08 #19

"Peter Morris" <peter[dot]morris(at)capableobjects.comwrote in message
news:OL****************@TK2MSFTNGP02.phx.gbl...
What occurs to me is that you only want something done once, so why put it
in the loop at all?

foreach (RaceCar currentRaceCar in RaceCarCollection)
currentRaceCar.Start();

RaceCarCollection[RaceCarCollection.Count - 1].BreakDown();
What does BreakDown do?

Thanks,

Tom
>

Mar 2 '08 #20
tshad skrev:
"Bjørn Brox" <bp****@gmail.comwrote in message
news:47********@news.broadpark.no...
>tshad skrev:
>>Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?

foreach (Racecar racecar in RaceCarCollection)
{
...

if last row do something?
}

You can tell how many items you have in the collection but is there way
to tell which row you are looking or if this is the last row?
Not without counying an test against RaceCarCollection.Count (or .Length)

Why not use a for loop instead?

I could.

But it wasn't a problem just a question.

At the moment, I just set iktr= 0 and just a line after the foreach line
(iktr++;) and then test against RaceCarCollection.Count as you mentioned.

I was just curious if there was a property somewhere that told you what line
in the collection you were on without having to do this.
Depends on what kind of object you have and how it is organized.
In your example: Is Racecar.Index an option?
>

--
Bjørn Brox
Mar 2 '08 #21

"Bjørn Brox" <bp****@gmail.comwrote in message
news:47********@news.broadpark.no...
tshad skrev:
>"Bjørn Brox" <bp****@gmail.comwrote in message
news:47********@news.broadpark.no...
>>tshad skrev:
Is there a way to know if you are looking at the last record record of
foreach loop other then setting up a loop counter that you manually
increment?

foreach (Racecar racecar in RaceCarCollection)
{
...

if last row do something?
}

You can tell how many items you have in the collection but is there way
to tell which row you are looking or if this is the last row?

Not without counying an test against RaceCarCollection.Count (or
.Length)

Why not use a for loop instead?

I could.

But it wasn't a problem just a question.

At the moment, I just set iktr= 0 and just a line after the foreach line
(iktr++;) and then test against RaceCarCollection.Count as you mentioned.

I was just curious if there was a property somewhere that told you what
line in the collection you were on without having to do this.

Depends on what kind of object you have and how it is organized.
In your example: Is Racecar.Index an option?
I don't know.

What is that?

Tom.
>
>>


--
Bjørn Brox

Mar 2 '08 #22
On Sun, 02 Mar 2008 09:52:09 -0800, tshad <tf*@dslextreme.comwrote:
[...]
In my example, I want to be able to do something on the last loop and
process it (as I do on the previous loops) without having to rewrite the
processing code outside of the loop:
So, if I understand correctly, not only do you want to do something
special when you reach the last element of the loop, the processing of
that last element is supposed to incorporate that "something special".

In that case, yes...there's a benefit to keeping that inside the loop and
tracking a counter may be a better solution. Noting, of course, that
that's mainly because you've said you do have a valid count for the
collection and so it's reasonable to make that test without any additional
work.

One remaining point: if your processing is some significant amount of code
(more than a couple of lines, for example), then I think it would be
almost as reasonable to put the processing into a separate method and then
call it from two places: inside the loop, and then at the end.

I say "almost", because doing that actually makes the loop more awkward.
It'd have to look something like this:

Racecar racecarPrev = null;

foreach (Racecar racecar in RaceCarCollection)
{
if (racecarPrev != null)
{
ProcessItem(racecarPrev);
}

racecarPrev = racecar;
}

if (racecarPrev != null)
{
// do "something special"
ProcessItem(racecarPrev);
}

That way you don't do the "ProcessItem" work until you know whether the
item is in fact the last one or not. Since the processing is encapsulated
in a separate method, I think it's less of a problem to duplicate that
call (I definitely don't like copy-and-pasting code that does real work,
but duplicating a simple call to a method isn't so bad if it's otherwise
beneficial).

Obviously you wouldn't contort your code to work like the above if you
already have a valid count for your collection and can do the "last item"
test inside the loop. But it could be worth keeping the above arrangement
in mind for dealing with collections that don't expose a count.

Pete
Mar 2 '08 #23

"Peter Morris" <peter[dot]morris(at)capableobjects.comwrote in message
news:OL****************@TK2MSFTNGP02.phx.gbl...
What occurs to me is that you only want something done once, so why put it
in the loop at all?
More likely, he wants something *not done* for the last item, for example
inserting a comma to separate items. That something may or may not be easy
to undo.
>
foreach (RaceCar currentRaceCar in RaceCarCollection)
currentRaceCar.Start();

RaceCarCollection[RaceCarCollection.Count - 1].BreakDown();


Mar 4 '08 #24

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Mike P | last post by:
In a foreach loop, how do you break out of the iteration but not the loop? Break and continue both seem to exit the loop, I need something that for example on an if statement will cease execution...
13
by: TrintCSD | last post by:
How can I reset the collections within a foreach to be read as a change from within the foreach loop then restart the foreach after collections has been changed? foreach(string invoice in...
18
by: Ken Varn | last post by:
Is there any way to reset a foreach loop to re-iterate through the collection as if it were starting from the beginning? Namely, if I delete an item out of a collection, I want to be able to reset...
5
by: David C | last post by:
This is very strange. Say I have code like this. I am simply looping through a collection object in a foreach loop. Course course = new Course(); foreach(Student s in course.Students) {...
3
by: cody | last post by:
Currently it is only legal to use types which has a method named GetEnumerator to be used in a foreach loop. This makes it impossible to use the same Enumerator after and before a foreach loop,...
10
by: fig000 | last post by:
HI, I'm new to generics. I've written a simple class to which I'm passing a generic list. I'm able to pass the list and even pass the type of the list so I can use it to traverse it. It's a...
1
by: Perl Beginner | last post by:
I hope i can articulate this question properly. i have been trying to figure this out for over a week. I am comparing the contents of two files, but the comparison is done inside of a foreach...
3
by: SM | last post by:
Hello, I have an array that holds images path of cd covers. The array looks like this: $cd = array( 589=>'sylver.jpg', 782=>'bigone.jpg', 158=>'dime.jpg' );
1
by: greyseal96 | last post by:
Hi, I am a pretty new programmer, so I apologize in andvance if this is a dumb question... In a book that I'm reading to learn C#, it says that when using a foreach() loop, a read-only copy of...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.