简体   繁体   English

c#中的foreach问题

[英]Foreach issue in c#

I'm writing a simple console note app, and having some issues with "foreach" function.我正在编写一个简单的控制台笔记应用程序,并且在“foreach”函数方面存在一些问题。 When I enter "View", the notes should be displayed in order, but for each note I get "0", instead '0' '1' '2'.当我输入“查看”时,笔记应该按顺序显示,但对于每个笔记,我得到“0”,而不是“0”“1”“2”。

笔记图片

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);
        }
    }
}

Three options here这里的三个选项

  1. Use the notes.IndexOf()使用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 循环

    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.请注意,无需在WriteLine()语句中将整数转换为字符串,因为字符串插值会自动执行此操作。

First, your variable names are confusing.首先,您的变量名称令人困惑。 change the foreach (string i in notes) to foreach (string note in notes) .foreach (string i in notes)更改为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)其次,在notes数组中寻找当前音符的索引,因此将i.IndexOf(i)改为notes.IndexOf(note)

 foreach (string note in notes) { int idx = notes.IndexOf(note); Console.WriteLine($"{Convert.ToString(idx)}. {note}"); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM