Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. The current index in the foreach

The current index in the foreach

Scheduled Pinned Locked Moved C#
csharpdatabasequestion
12 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C Offline
    C Offline
    cazzz
    wrote on last edited by
    #1

    Just a quickie for many thanks; In a for loop I can get my current index quit easy; for (int i=0; i<8; ++i) Console.WriteLine("Current index = "+i); But with a foreach statement it's different. I only know this ugly way; int i=0; foreach (int curInt in intCollection) { Console.WriteLine("Current index = "+i); i++; } Maybe I'm asking the impossible because foreach is for collections so it doesn't have a strict index. But Maybe there's an index keyword? Couldn't find it at the MSDN C# site.

    J 1 Reply Last reply
    0
    • C cazzz

      Just a quickie for many thanks; In a for loop I can get my current index quit easy; for (int i=0; i<8; ++i) Console.WriteLine("Current index = "+i); But with a foreach statement it's different. I only know this ugly way; int i=0; foreach (int curInt in intCollection) { Console.WriteLine("Current index = "+i); i++; } Maybe I'm asking the impossible because foreach is for collections so it doesn't have a strict index. But Maybe there's an index keyword? Couldn't find it at the MSDN C# site.

      J Offline
      J Offline
      jan larsen
      wrote on last edited by
      #2

      And you won't find any. The ugly way is the only way to do it. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

      C 1 Reply Last reply
      0
      • J jan larsen

        And you won't find any. The ugly way is the only way to do it. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

        C Offline
        C Offline
        cazzz
        wrote on last edited by
        #3

        Ow well that's to bad. Is there any reason to use a foreach instead off a for loop? My objections for using a foreach are; - 'Ugly' indexing, as stated above - Collection can't be modified while foreach-ing the collection.

        J J P 3 Replies Last reply
        0
        • C cazzz

          Ow well that's to bad. Is there any reason to use a foreach instead off a for loop? My objections for using a foreach are; - 'Ugly' indexing, as stated above - Collection can't be modified while foreach-ing the collection.

          J Offline
          J Offline
          Judah Gabriel Himango
          wrote on last edited by
          #4

          Use a for loop if you need indexing. Use foreach if you don't need indexing and you like syntax candy.

          Tech, life, family, faith: Give me a visit. I'm currently blogging about: Homosexuality in Christianity Judah Himango

          M 1 Reply Last reply
          0
          • C cazzz

            Ow well that's to bad. Is there any reason to use a foreach instead off a for loop? My objections for using a foreach are; - 'Ugly' indexing, as stated above - Collection can't be modified while foreach-ing the collection.

            J Offline
            J Offline
            jan larsen
            wrote on last edited by
            #5

            foreach is great when you're abstracting your code. Indexing is purely for lists, and if you're doing a foreach on an IEnumerable, then you're always sure to get the maximum performance. Consider the performance issues on indexing eg. a linked list or a binary tree. I'm always declaring my collection member variables as the lowest denominator. Eg. if I need a map, then I'm declaring an IDictionary, and when I'm iterating through the elements, I'll use a foreach loop. This means that if I am to use a counter, then I have to do it the ugly way. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

            L 1 Reply Last reply
            0
            • J jan larsen

              foreach is great when you're abstracting your code. Indexing is purely for lists, and if you're doing a foreach on an IEnumerable, then you're always sure to get the maximum performance. Consider the performance issues on indexing eg. a linked list or a binary tree. I'm always declaring my collection member variables as the lowest denominator. Eg. if I need a map, then I'm declaring an IDictionary, and when I'm iterating through the elements, I'll use a foreach loop. This means that if I am to use a counter, then I have to do it the ugly way. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

              L Offline
              L Offline
              Libor Tinka
              wrote on last edited by
              #6

              You can use IndexOf property of the collection you use, but since you're using foreach, there's no reason to think about indexes.

              J 1 Reply Last reply
              0
              • J Judah Gabriel Himango

                Use a for loop if you need indexing. Use foreach if you don't need indexing and you like syntax candy.

                Tech, life, family, faith: Give me a visit. I'm currently blogging about: Homosexuality in Christianity Judah Himango

                M Offline
                M Offline
                Matt Gerrans
                wrote on last edited by
                #7

                It isn't about whether you "like syntax candy," it is about whether you like writing quality code. See Jan Larsen's reply for more insight. Matt Gerrans

                J 1 Reply Last reply
                0
                • M Matt Gerrans

                  It isn't about whether you "like syntax candy," it is about whether you like writing quality code. See Jan Larsen's reply for more insight. Matt Gerrans

                  J Offline
                  J Offline
                  Judah Gabriel Himango
                  wrote on last edited by
                  #8

                  I'm not against using foreach, I use it quite a lot in my code. I just don't agree that 'foreach' is quality where 'for' is not. Both are easily recognizable by any novice programmer. As I said to the origin poster, if you need an index, you might as well be using for instead of foreach. The IEnumerable idea is cool, and gets even better with C# 2.0's iterators with the yield keyword (allowing you to, basically, write co-routines). Coupled with foreach, it is really great. That doesn't mean we should never use the 'for' keyword. My 'syntax candy' statement wasn't meant to belittle IEnumerable or foreach keyword; I'm merely saying that it is a simple syntax expression that does a lot under the hood (initialize an Enumerator, call the appropriate method calls each loop, and return the next object in the enumeration). You could call your own GetNext() and other appropriate IEnumerator functions yourself, 'foreach' is syntax candy that allows you to forgo typing all that.

                  Tech, life, family, faith: Give me a visit. I'm currently blogging about: Homosexuality in Christianity Judah Himango

                  J 1 Reply Last reply
                  0
                  • L Libor Tinka

                    You can use IndexOf property of the collection you use, but since you're using foreach, there's no reason to think about indexes.

                    J Offline
                    J Offline
                    jan larsen
                    wrote on last edited by
                    #9

                    ltinka wrote: You can use IndexOf property of the collection you use Well, not really since there is no definite index in a map. Talking lists I definately agree, in a linked list, IndexOf() would trigger a reiteration, so it would have been better to use indexing in the first place. "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

                    1 Reply Last reply
                    0
                    • J Judah Gabriel Himango

                      I'm not against using foreach, I use it quite a lot in my code. I just don't agree that 'foreach' is quality where 'for' is not. Both are easily recognizable by any novice programmer. As I said to the origin poster, if you need an index, you might as well be using for instead of foreach. The IEnumerable idea is cool, and gets even better with C# 2.0's iterators with the yield keyword (allowing you to, basically, write co-routines). Coupled with foreach, it is really great. That doesn't mean we should never use the 'for' keyword. My 'syntax candy' statement wasn't meant to belittle IEnumerable or foreach keyword; I'm merely saying that it is a simple syntax expression that does a lot under the hood (initialize an Enumerator, call the appropriate method calls each loop, and return the next object in the enumeration). You could call your own GetNext() and other appropriate IEnumerator functions yourself, 'foreach' is syntax candy that allows you to forgo typing all that.

                      Tech, life, family, faith: Give me a visit. I'm currently blogging about: Homosexuality in Christianity Judah Himango

                      J Offline
                      J Offline
                      jan larsen
                      wrote on last edited by
                      #10

                      Judah Himango wrote: My 'syntax candy' statement wasn't meant to belittle IEnumerable or foreach keyword; I'm merely saying that it is a simple syntax expression that does a lot under the hood (initialize an Enumerator, call the appropriate method calls each loop, and return the next object in the enumeration). You could call your own GetNext() and other appropriate IEnumerator functions yourself, 'foreach' is syntax candy that allows you to forgo typing all that. Basically, that's what high level languages are all about :-), I've done my share of Java programming, and I can assure you that I don't miss this:

                      for (Iterator i = myList.iterator(); i.hasNext();)
                      {
                      String tmp = (String) i.next();
                      }

                      I'd rather do this:

                      foreach(String tmp in myList)
                      {
                      }

                      Eye candy maybe, but much clearer, and I guess the ease of use, has got more inexperienced programmers to use the correct iterating technique. I'm not joking, I've had colleques that would use this on a linked list:

                      for (int i = 0; i < myList.size(); i++)
                      {
                      String tmp = (String) myList.get(i);
                      }

                      "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

                      1 Reply Last reply
                      0
                      • C cazzz

                        Ow well that's to bad. Is there any reason to use a foreach instead off a for loop? My objections for using a foreach are; - 'Ugly' indexing, as stated above - Collection can't be modified while foreach-ing the collection.

                        P Offline
                        P Offline
                        Patric_J
                        wrote on last edited by
                        #11

                        cazzz wrote: Is there any reason to use a foreach instead off a for loop? Using foreach will automatically cast an item in the collection to right type. Example:

                        for (int i = 0; i < 8; ++i)
                        {
                        // You need to cast.
                        Customer cust = (Customer)customers[i];
                        }

                        instead

                        foreach (Customer cust in customers)
                        {
                        // cust is now of correct type Customer.
                        }

                        Use foreach when you just want to iterate over all items and don't care about order or which item is the current item. Handle special behaviour inside a class and not in the calling code according to classic OO principles. Example:

                        // Calling code somehow knows that customers[4] needs some special handling.
                        for (int i = 0; i < 8; ++i)
                        {
                        if (i == 4)
                        {
                        Customer cust = (Customer)customers[i];
                        DoSumthingWithCustomer(cust);
                        }
                        }

                        instead

                        // Calling code only knows it needs to call a method for each customer object.
                        foreach (Customer cust in customers)
                        {
                        // cust is now of correct type Customer.
                        cust.DoSumthing();
                        }

                        You should implement the class Customer so when calling method DoSumthing() on its objects it will only do something for the object which have index 4 in the for loop. Ugly indexing is normally not needed in my experience. /Patric My C# blog: C# Coach

                        J 1 Reply Last reply
                        0
                        • P Patric_J

                          cazzz wrote: Is there any reason to use a foreach instead off a for loop? Using foreach will automatically cast an item in the collection to right type. Example:

                          for (int i = 0; i < 8; ++i)
                          {
                          // You need to cast.
                          Customer cust = (Customer)customers[i];
                          }

                          instead

                          foreach (Customer cust in customers)
                          {
                          // cust is now of correct type Customer.
                          }

                          Use foreach when you just want to iterate over all items and don't care about order or which item is the current item. Handle special behaviour inside a class and not in the calling code according to classic OO principles. Example:

                          // Calling code somehow knows that customers[4] needs some special handling.
                          for (int i = 0; i < 8; ++i)
                          {
                          if (i == 4)
                          {
                          Customer cust = (Customer)customers[i];
                          DoSumthingWithCustomer(cust);
                          }
                          }

                          instead

                          // Calling code only knows it needs to call a method for each customer object.
                          foreach (Customer cust in customers)
                          {
                          // cust is now of correct type Customer.
                          cust.DoSumthing();
                          }

                          You should implement the class Customer so when calling method DoSumthing() on its objects it will only do something for the object which have index 4 in the for loop. Ugly indexing is normally not needed in my experience. /Patric My C# blog: C# Coach

                          J Offline
                          J Offline
                          jan larsen
                          wrote on last edited by
                          #12

                          Patric_J wrote: Ugly indexing is normally not needed in my experience. I beg to differ. More often than not these days, I find myself writing stuff like this:

                          protected void DoSomething(MySortedStringList sortedElements, string[] buffer)
                          {
                          int i = 0;
                          foreach (string element in sortedElements)
                          {
                          buffer[i++] = element;
                          }

                          }

                          But that's what happens when having Hashtable as favourite collection :rolleyes: "God doesn't play dice" - Albert Einstein "God not only plays dice, He sometimes throws the dices where they cannot be seen" - Niels Bohr

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups