473,387 Members | 1,789 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,387 software developers and data experts.

sequence of foreach

Hi,

does foreach guarantees the sequence order starting from index 0 ?

--
rgds, Wilfried [MapPoint MVP]
http://www.mestdagh.biz
Nov 1 '06 #1
11 3668
Wilfried,

foreach uses an IEnumerator returned by the collection. So it depends
on how the IEnumerator is implemented and who provided it.

In the case of an array, ArrayList, or List<Tthen yes. The order is
defined by the index in the collection.

Which collection are you referring to?

Brian

Wilfried Mestdagh wrote:
Hi,

does foreach guarantees the sequence order starting from index 0 ?

--
rgds, Wilfried [MapPoint MVP]
http://www.mestdagh.biz
Nov 1 '06 #2
No, I don't think so. You could for example do:

System.Object[] list = new System.Object[3] {2, 3, "This is printed."};
foreach (string item in list)
System.Console.WriteLine(item.ToString());

The foreach loop (I think) only picks up the string at index 2, so it
doesn't start at 0.
However, as far as I've seen (and counted on in several applications),
it does seem the foreach loops through the list/array from index 0 to
the end. So it seems items with lower indexes tend to come first.

Nov 1 '06 #3
No, but yes. Ish.

Iterators can legitimately return in any order... for instance, you can get
iterators whose entire purpose is to iterate backwards over a set of date.
However for common lists, collections, arrays etc it does go forwards.

Note that dictionaries and hashtables do not guarantee to preserve order at
the point of insertion.

Marc
Nov 1 '06 #4
Actually, that will raise an invalid cast exception. foreach does not skip
badly typed data. However, I believe that LINQ (3.0) introduces this
capability into the standard queries (via the OfType operator).

Marc
Nov 1 '06 #5
Hi Brian,

DataTable.Rows
foreach (DataRow row in dataTable.Rows)
...

It seems to come in the right sequence in a few experiments I have done,
but wanted to be sure.

--
rgds, Wilfried [MapPoint MVP]
http://www.mestdagh.biz

Brian Gideon wrote:
Wilfried,

foreach uses an IEnumerator returned by the collection. So it depends
on how the IEnumerator is implemented and who provided it.

In the case of an array, ArrayList, or List<Tthen yes. The order is
defined by the index in the collection.

Which collection are you referring to?

Brian

Wilfried Mestdagh wrote:
>Hi,

does foreach guarantees the sequence order starting from index 0 ?

--
rgds, Wilfried [MapPoint MVP]
http://www.mestdagh.biz
Nov 1 '06 #6
Hi Marc,

So if I understeand well, it is best if not sure to do a small
testproject to see how it is implemented ? And the direction per
collection type will always be the same ?

--
rgds, Wilfried [MapPoint MVP]
http://www.mestdagh.biz

Marc Gravell wrote:
No, but yes. Ish.

Iterators can legitimately return in any order... for instance, you can get
iterators whose entire purpose is to iterate backwards over a set of date.
However for common lists, collections, arrays etc it does go forwards.

Note that dictionaries and hashtables do not guarantee to preserve order at
the point of insertion.

Marc

Nov 1 '06 #7
Also an enumerator may not have any index and just yield results until some
condition. For example, you could return and enumerator on a Producer class
that somehow produces objects and just foreach over it. Standard collection
enumerators will start at 0 and go till end in order. So it all depends on
the implementation of the IEnumerator. For example, you could step, or go
in reverse, etc.

--
William Stacey [C# MVP]

"Wilfried Mestdagh" <wi******@mestdagh.bizwrote in message
news:eQ**************@TK2MSFTNGP04.phx.gbl...
| Hi,
|
| does foreach guarantees the sequence order starting from index 0 ?
|
| --
| rgds, Wilfried [MapPoint MVP]
| http://www.mestdagh.biz
Nov 2 '06 #8
Actually, if in doubt I'd just RTM. Test cases aren't proof positive:
I've seen someone argue that Dictionary preserves sort order because a
test case says so. Simple fact is that Dictionary *sometimes* preserves
sort order, either by conincidence or small data sets... who knows.

As stated, most "standard" (if that term apples) inbuilt sets iterate
strictly forwards... but you can normally check, for instance
Array.GetEnumerator() [which underpins the foreach compiler support]:

http://msdn2.microsoft.com/en-us/lib...numerator.aspx
<quote>
Initially, the enumerator is positioned before the first element in the
collection. Reset also brings the enumerator back to this position.
<snip/>
Current returns the same object until either MoveNext or Reset is
called. MoveNext sets Current to the next element.
<snip/>
If MoveNext passes the end of the collection, the enumerator is
positioned after the last element in the collection and MoveNext
returns false.
</quote>

This translates as "foreach goes from 0 to Length-1"

However, as pointed out by William, not all enumerators do this. You
can define for instance infinite enumerators (fibonacci numbers
perhaps? random numbers? annoying paperclip messages?), or a single set
can support multiple enumerators (via separate accessor properties /
methods), such as .GetEnumerator(), ReverseOrder.GetEnumerator(),
AlphabeticalOrder.GetEnumerator(), whatever. These would have to be
defined by whatever class implements them, of course ;-p

Marc

Nov 2 '06 #9
Hi Marc and others,

Thank you for good explanation. I have used it now in:
DataTable.Rows
foreach (DataRow row in dataTable.Rows)

Is this one OK ?

--
rgds, Wilfried [MapPoint MVP]
http://www.mestdagh.biz
Nov 2 '06 #10
yup

And it is a reasonable default assumption for most containers... really I
think everyone was just trying to make you aware that it isn't a guarantee
;-p

Happy coding,

Marc
Nov 2 '06 #11
Hi Marc,

Thx :)

--
rgds, Wilfried [MapPoint MVP]
http://www.mestdagh.biz
Nov 2 '06 #12

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

Similar topics

1
by: Paul Porcelli | last post by:
I have the following code(excerpt) which grabs some lines from a syslog file and adds any found in the range to an array. @lines=();@vvlines=(); $t = new Net::Telnet (Timeout => 30, Prompt =>...
32
by: James Curran | last post by:
I'd like to make the following proposal for a new feature for the C# language. I have no connection with the C# team at Microsoft. I'm posting it here to gather input to refine it, in an "open...
3
by: cody | last post by:
why foreach does always have to declare a new variable? I have to write foreach (int n in array){} but Iam not allowed to write: int n=0; foreach (n in array){}
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...
27
by: Tripper | last post by:
Which is the better way to go and why? //trivial example List<string> strings = GetStrings(); foreach (string s in strings) { // some operation; } strings.ForEach(
3
by: Wiktor Zychla [C# MVP] | last post by:
since generics allow us to implement several IEnumerable<T> interfaces on a single class, I think that "foreach" should somehow reflect that. suppose we have a enumerable class class C :...
1
davydany
by: davydany | last post by:
Hey guys...a n00b Here for this site. I'm making a sequence class for my C++ class. And The thing is in the array that I have, lets say i put in {13,17,38,18}, when i see the current values for the...
2
by: raylopez99 | last post by:
Here is a short program demonstrating using IEnumberable, Linq, predicates, extension methods and some tricks and how to convert an IEnumberable sequence into an array. For future reference, not...
2
by: peter stickney | last post by:
I am running CentOS 5.2, with all current updates PHP 5.1.6 - PHP 5.1.6 (cli) (built: Jul 16 2008 19:53:00) Copyright (c) 1997-2006 The PHP Group Zend Engine v2.1.0, Copyright (c) 1998-2006...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.