Home > Mobile >  Foreach issue in c#
Foreach issue in c#

Time:11-05

I'm writing a simple console note app, and having some issues with "foreach" function. When I enter "View", the notes should be displayed in order, but for each note I get "0", instead '0' '1' '2'.

notes pic

using System;
using System.Collections.Generic;

namespace note_app_console

{
    class Program
    {
        static void Main(string[] args)

        {
            List <String> notes = new List<string>();
            Console.WriteLine("Notes");
            int userInput;
            

            //main loop
            do
            {
                string addNote;
                //selecting action from menu
                userInput = Convert.ToInt32(Console.ReadLine());

                switch (userInput)
                {
                    case 1:

                        Console.WriteLine("Enter the note content: ");
                        addNote = Console.ReadLine();
                        notes.Add(addNote);
                        Console.WriteLine("Note added.");
                        break;

                    case 2:

                        Console.WriteLine("Your notes: ");
                        foreach (string i in notes)
                        {
                            int indexNote = i.IndexOf(i);
                            Console.WriteLine($"{Convert.ToString(indexNote)}. {i}");
                            

                        }

                        break;

                        
                }
                
            } while (userInput != 4);
        }
    }
}

CodePudding user response:

Three options here

  1. Use the notes.IndexOf()

    foreach (string item in notes)
    {
        int indexNote = notes.IndexOf(item);
        Console.WriteLine($"{indexNote}. {item}");                                                   
    }
    
  2. Use a counter

    int counter = 0;
    foreach (string item in notes)
    {
        Console.WriteLine($"{counter}. {item}");                                                   
        counter  ;
    }
    
  3. Use a for loop

    for(int i=0; i<notes.Count; i  )
    {
        Console.WriteLine($"{i}. {notes[i]}");                                                   
    }
    

Note that there is no need to convert the integer into a string in the WriteLine() statement as the string interpolation does that automatically.

CodePudding user response:

First, your variable names are confusing. change the foreach (string i in notes) to foreach (string note in notes).

Second, look for the index of the current note in the notes array, so change the i.IndexOf(i) to notes.IndexOf(note)

foreach (string note in notes)
{
    int idx = notes.IndexOf(note);
    Console.WriteLine($"{Convert.ToString(idx)}. {note}");
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related