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. beginner question: foreach .. else?

beginner question: foreach .. else?

Scheduled Pinned Locked Moved C#
csharpquestionlearningdelphilinq
8 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.
  • T Offline
    T Offline
    Ted On The Net
    wrote on last edited by
    #1

    hi, I'm just learning C# after being a Delphi coder for waayyy to long :D I was wondering, why isn't it possible to use an else statement with the foreach statement? Check out my quick and dirty demo code:

    namespace ConsoleApplication
    {
    class Product
    {
    public string Code { get; set; }
    public string Description { get; set; }

    }
    
    class Program
    {
        static void Main(string\[\] args)
        {
            //create some enumerable list
            IEnumerable<Product> myProductList = new List<Product>
                                         {
                                             new Product() {Code = "CDR", Description = "CD-Rom"},
                                             new Product() {Code = "DVD", Description = "DVD-Rom"},
                                             new Product() {Code = "BRD", Description = "BlueRay Disc"},
                                         };
    
            //select some products with LINQ
            var myProductSelection = (from aProduct in myProductList where aProduct.Code.StartsWith("R") select aProduct);
    
            //Print header text
            Console.WriteLine("The products that were found:");
    
            //loop through products in selection
            foreach (var aProduct in myProductSelection)
            {
                Console.WriteLine("Found product: " + aProduct.Code);
            }
          
            //pause to check results
            Console.ReadKey();            
        }
    }
    

    }

    The above code returns nothing, since none of the product codes start with a "R". Would be nice if I could do this when my result is empty:

    //Print header text
    Console.WriteLine("The products that were found:");

    //loop through products in selection
    foreach (var aProduct in myProductSelection)
    {
    Console.WriteLine("Found product: " + aProduct.Code);
    }
    else
    {
    Console.WriteLine("No products were found!");
    }

    Just some ranting.. any good solutions to this unlike something like this?

    //Print header text
    Console.WriteLine("The products that were found:");

    int x = 0;
    //loop through products in selection
    foreach (var aProduct in myProductSelection)
    {
    x++;
    Console.WriteLine("Found product: " + aProduct.Code);
    }

    if (x > 0)
    Console.WriteLine("No products were found!");

    thx for any suggestions offered :)

    - Life would be so much easier if I had the source code! - If C#

    L K P S 4 Replies Last reply
    0
    • T Ted On The Net

      hi, I'm just learning C# after being a Delphi coder for waayyy to long :D I was wondering, why isn't it possible to use an else statement with the foreach statement? Check out my quick and dirty demo code:

      namespace ConsoleApplication
      {
      class Product
      {
      public string Code { get; set; }
      public string Description { get; set; }

      }
      
      class Program
      {
          static void Main(string\[\] args)
          {
              //create some enumerable list
              IEnumerable<Product> myProductList = new List<Product>
                                           {
                                               new Product() {Code = "CDR", Description = "CD-Rom"},
                                               new Product() {Code = "DVD", Description = "DVD-Rom"},
                                               new Product() {Code = "BRD", Description = "BlueRay Disc"},
                                           };
      
              //select some products with LINQ
              var myProductSelection = (from aProduct in myProductList where aProduct.Code.StartsWith("R") select aProduct);
      
              //Print header text
              Console.WriteLine("The products that were found:");
      
              //loop through products in selection
              foreach (var aProduct in myProductSelection)
              {
                  Console.WriteLine("Found product: " + aProduct.Code);
              }
            
              //pause to check results
              Console.ReadKey();            
          }
      }
      

      }

      The above code returns nothing, since none of the product codes start with a "R". Would be nice if I could do this when my result is empty:

      //Print header text
      Console.WriteLine("The products that were found:");

      //loop through products in selection
      foreach (var aProduct in myProductSelection)
      {
      Console.WriteLine("Found product: " + aProduct.Code);
      }
      else
      {
      Console.WriteLine("No products were found!");
      }

      Just some ranting.. any good solutions to this unlike something like this?

      //Print header text
      Console.WriteLine("The products that were found:");

      int x = 0;
      //loop through products in selection
      foreach (var aProduct in myProductSelection)
      {
      x++;
      Console.WriteLine("Found product: " + aProduct.Code);
      }

      if (x > 0)
      Console.WriteLine("No products were found!");

      thx for any suggestions offered :)

      - Life would be so much easier if I had the source code! - If C#

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      Ted On The Net wrote:

      Just some ranting.. any good solutions to this unlike something like this?

      I can only think of 1 fundamentally different solution - explicitly test for the number of items in myProductSelection. Personally I would set a bool to true in the foreach rather than counting the iterations, but that is not that much different from the solution you gave. There is no build-in way to do this, as far as I know.

      1 Reply Last reply
      0
      • T Ted On The Net

        hi, I'm just learning C# after being a Delphi coder for waayyy to long :D I was wondering, why isn't it possible to use an else statement with the foreach statement? Check out my quick and dirty demo code:

        namespace ConsoleApplication
        {
        class Product
        {
        public string Code { get; set; }
        public string Description { get; set; }

        }
        
        class Program
        {
            static void Main(string\[\] args)
            {
                //create some enumerable list
                IEnumerable<Product> myProductList = new List<Product>
                                             {
                                                 new Product() {Code = "CDR", Description = "CD-Rom"},
                                                 new Product() {Code = "DVD", Description = "DVD-Rom"},
                                                 new Product() {Code = "BRD", Description = "BlueRay Disc"},
                                             };
        
                //select some products with LINQ
                var myProductSelection = (from aProduct in myProductList where aProduct.Code.StartsWith("R") select aProduct);
        
                //Print header text
                Console.WriteLine("The products that were found:");
        
                //loop through products in selection
                foreach (var aProduct in myProductSelection)
                {
                    Console.WriteLine("Found product: " + aProduct.Code);
                }
              
                //pause to check results
                Console.ReadKey();            
            }
        }
        

        }

        The above code returns nothing, since none of the product codes start with a "R". Would be nice if I could do this when my result is empty:

        //Print header text
        Console.WriteLine("The products that were found:");

        //loop through products in selection
        foreach (var aProduct in myProductSelection)
        {
        Console.WriteLine("Found product: " + aProduct.Code);
        }
        else
        {
        Console.WriteLine("No products were found!");
        }

        Just some ranting.. any good solutions to this unlike something like this?

        //Print header text
        Console.WriteLine("The products that were found:");

        int x = 0;
        //loop through products in selection
        foreach (var aProduct in myProductSelection)
        {
        x++;
        Console.WriteLine("Found product: " + aProduct.Code);
        }

        if (x > 0)
        Console.WriteLine("No products were found!");

        thx for any suggestions offered :)

        - Life would be so much easier if I had the source code! - If C#

        K Offline
        K Offline
        kevinnicol
        wrote on last edited by
        #3

        does myProductSelection have a count or a length? Most strucutres that implement IEnumerable do. If so just check to see if the count is greater than zero.

        T 1 Reply Last reply
        0
        • K kevinnicol

          does myProductSelection have a count or a length? Most strucutres that implement IEnumerable do. If so just check to see if the count is greater than zero.

          T Offline
          T Offline
          Ted On The Net
          wrote on last edited by
          #4

          yes, it does. One could implement it like this:

          if (myProductSelection.Count() != 0)
          {
          //loop through products in selection
          foreach (var aProduct in myProductSelection)
          {
          Console.WriteLine("Found product:" + aProduct.Code);
          }
          }
          else
          {
          Console.WriteLine("No products found!");
          }

          But why should I? If the foreach loop doesn't get executed, I know I've got the same result as if I used the above if-statement. So imo this gives me redundant code. Or do you disagree?

          - Life would be so much easier if I had the source code! - If C# had true garbage collection, most applications would delete themselves upon execution ;)

          R 1 Reply Last reply
          0
          • T Ted On The Net

            hi, I'm just learning C# after being a Delphi coder for waayyy to long :D I was wondering, why isn't it possible to use an else statement with the foreach statement? Check out my quick and dirty demo code:

            namespace ConsoleApplication
            {
            class Product
            {
            public string Code { get; set; }
            public string Description { get; set; }

            }
            
            class Program
            {
                static void Main(string\[\] args)
                {
                    //create some enumerable list
                    IEnumerable<Product> myProductList = new List<Product>
                                                 {
                                                     new Product() {Code = "CDR", Description = "CD-Rom"},
                                                     new Product() {Code = "DVD", Description = "DVD-Rom"},
                                                     new Product() {Code = "BRD", Description = "BlueRay Disc"},
                                                 };
            
                    //select some products with LINQ
                    var myProductSelection = (from aProduct in myProductList where aProduct.Code.StartsWith("R") select aProduct);
            
                    //Print header text
                    Console.WriteLine("The products that were found:");
            
                    //loop through products in selection
                    foreach (var aProduct in myProductSelection)
                    {
                        Console.WriteLine("Found product: " + aProduct.Code);
                    }
                  
                    //pause to check results
                    Console.ReadKey();            
                }
            }
            

            }

            The above code returns nothing, since none of the product codes start with a "R". Would be nice if I could do this when my result is empty:

            //Print header text
            Console.WriteLine("The products that were found:");

            //loop through products in selection
            foreach (var aProduct in myProductSelection)
            {
            Console.WriteLine("Found product: " + aProduct.Code);
            }
            else
            {
            Console.WriteLine("No products were found!");
            }

            Just some ranting.. any good solutions to this unlike something like this?

            //Print header text
            Console.WriteLine("The products that were found:");

            int x = 0;
            //loop through products in selection
            foreach (var aProduct in myProductSelection)
            {
            x++;
            Console.WriteLine("Found product: " + aProduct.Code);
            }

            if (x > 0)
            Console.WriteLine("No products were found!");

            thx for any suggestions offered :)

            - Life would be so much easier if I had the source code! - If C#

            P Offline
            P Offline
            Paulo Zemek
            wrote on last edited by
            #5

            I understand why you want this, but there is no implicit way of doing it. But, think that using foreach is a replacement for getting the enumerator, calling while(enumerator.MoveNext()) and setting a variable to enumerator.Current. (and at the end calling Dispose, if possible). So, the best solution for this is doing something like:

            using(var enumerator = enumerable.GetEnumerator())
            {
            if (enumerator.MoveNext())
            {
            do
            {
            var someVariable = enumerator.Current;

              ... the loop code...
            }
            while(enumerator.MoveNext());
            

            }
            else
            {
            ... the else you want ...
            }
            }

            And you can even create a method using delegates Action<T> for the value and non-generic Action for the else. Something like:

            ForEachOrElse(IEnumerable<T> enumerable, Action<T> actionForEachValue, action elseAction)

            And to use it you call something like:

            ForEachOrElse
            (
            enumerable,
            (value) =>
            {
            ... the code for each value...
            },
            () =>
            {
            ... the code for else ...
            }
            );

            modified on Tuesday, March 9, 2010 9:34 AM

            L 1 Reply Last reply
            0
            • P Paulo Zemek

              I understand why you want this, but there is no implicit way of doing it. But, think that using foreach is a replacement for getting the enumerator, calling while(enumerator.MoveNext()) and setting a variable to enumerator.Current. (and at the end calling Dispose, if possible). So, the best solution for this is doing something like:

              using(var enumerator = enumerable.GetEnumerator())
              {
              if (enumerator.MoveNext())
              {
              do
              {
              var someVariable = enumerator.Current;

                ... the loop code...
              }
              while(enumerator.MoveNext());
              

              }
              else
              {
              ... the else you want ...
              }
              }

              And you can even create a method using delegates Action<T> for the value and non-generic Action for the else. Something like:

              ForEachOrElse(IEnumerable<T> enumerable, Action<T> actionForEachValue, action elseAction)

              And to use it you call something like:

              ForEachOrElse
              (
              enumerable,
              (value) =>
              {
              ... the code for each value...
              },
              () =>
              {
              ... the code for else ...
              }
              );

              modified on Tuesday, March 9, 2010 9:34 AM

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #6

              Well no offense, but I'm not really convinced that this is the best solution - it is rather confusing especially to people who never "manually" used an enumerator..

              1 Reply Last reply
              0
              • T Ted On The Net

                yes, it does. One could implement it like this:

                if (myProductSelection.Count() != 0)
                {
                //loop through products in selection
                foreach (var aProduct in myProductSelection)
                {
                Console.WriteLine("Found product:" + aProduct.Code);
                }
                }
                else
                {
                Console.WriteLine("No products found!");
                }

                But why should I? If the foreach loop doesn't get executed, I know I've got the same result as if I used the above if-statement. So imo this gives me redundant code. Or do you disagree?

                - Life would be so much easier if I had the source code! - If C# had true garbage collection, most applications would delete themselves upon execution ;)

                R Offline
                R Offline
                riced
                wrote on last edited by
                #7

                Ted On The Net wrote:

                But why should I?

                Because it expresses the intention of the code? I.e. if there are items loop through them otherwise produce message. :)

                Regards David R --------------------------------------------------------------- "Every program eventually becomes rococo, and then rubble." - Alan Perlis

                1 Reply Last reply
                0
                • T Ted On The Net

                  hi, I'm just learning C# after being a Delphi coder for waayyy to long :D I was wondering, why isn't it possible to use an else statement with the foreach statement? Check out my quick and dirty demo code:

                  namespace ConsoleApplication
                  {
                  class Product
                  {
                  public string Code { get; set; }
                  public string Description { get; set; }

                  }
                  
                  class Program
                  {
                      static void Main(string\[\] args)
                      {
                          //create some enumerable list
                          IEnumerable<Product> myProductList = new List<Product>
                                                       {
                                                           new Product() {Code = "CDR", Description = "CD-Rom"},
                                                           new Product() {Code = "DVD", Description = "DVD-Rom"},
                                                           new Product() {Code = "BRD", Description = "BlueRay Disc"},
                                                       };
                  
                          //select some products with LINQ
                          var myProductSelection = (from aProduct in myProductList where aProduct.Code.StartsWith("R") select aProduct);
                  
                          //Print header text
                          Console.WriteLine("The products that were found:");
                  
                          //loop through products in selection
                          foreach (var aProduct in myProductSelection)
                          {
                              Console.WriteLine("Found product: " + aProduct.Code);
                          }
                        
                          //pause to check results
                          Console.ReadKey();            
                      }
                  }
                  

                  }

                  The above code returns nothing, since none of the product codes start with a "R". Would be nice if I could do this when my result is empty:

                  //Print header text
                  Console.WriteLine("The products that were found:");

                  //loop through products in selection
                  foreach (var aProduct in myProductSelection)
                  {
                  Console.WriteLine("Found product: " + aProduct.Code);
                  }
                  else
                  {
                  Console.WriteLine("No products were found!");
                  }

                  Just some ranting.. any good solutions to this unlike something like this?

                  //Print header text
                  Console.WriteLine("The products that were found:");

                  int x = 0;
                  //loop through products in selection
                  foreach (var aProduct in myProductSelection)
                  {
                  x++;
                  Console.WriteLine("Found product: " + aProduct.Code);
                  }

                  if (x > 0)
                  Console.WriteLine("No products were found!");

                  thx for any suggestions offered :)

                  - Life would be so much easier if I had the source code! - If C#

                  S Offline
                  S Offline
                  StarBP
                  wrote on last edited by
                  #8

                  //Print header text
                  Console.WriteLine("The products that were found:");

                  //loop through products in selection
                  foreach (var aProduct in myProductSelection)
                  {
                  Console.WriteLine("Found product: " + aProduct.Code);
                  }
                  else
                  {
                  Console.WriteLine("No products were found!");
                  }

                  Try this:

                  //Print header text
                  Console.WriteLine("The products that were found:");

                  //Initialize tracker variable
                  int productsFound = 0;

                  //loop through products in selection
                  foreach (var aProduct in myProductSelection)
                  {
                  Console.WriteLine("Found product: " + aProduct.Code);
                  productsFound++;
                  }

                  if (productsFound == 0)
                  Console.WriteLine("No products were found!");

                  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