[英]Foreach issue in c#
我正在编写一个简单的控制台笔记应用程序,并且在“foreach”函数方面存在一些问题。 当我输入“查看”时,笔记应该按顺序显示,但对于每个笔记,我得到“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);
}
}
}
这里的三个选项
使用notes.IndexOf()
foreach (string item in notes) { int indexNote = notes.IndexOf(item); Console.WriteLine($"{indexNote}. {item}"); }
使用计数器
int counter = 0; foreach (string item in notes) { Console.WriteLine($"{counter}. {item}"); counter++; }
使用 for 循环
for(int i=0; i<notes.Count; i++) { Console.WriteLine($"{i}. {notes[i]}"); }
请注意,无需在WriteLine()
语句中将整数转换为字符串,因为字符串插值会自动执行此操作。
首先,您的变量名称令人困惑。 将foreach (string i in notes)
更改为foreach (string note in notes)
。
其次,在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.