我自学自我C#并一直在试图弄清楚如何让用户能够从列表中删除一个项目及其索引号通过输入自己的索引号或键入单词。允许用户从列表中删除项目
我已经一派,尝试了许多方法来做到这一点,但每次我想出了一个办法时,它会删除元素我会选择,但指数并没有消失。示例(列表:0.hat,1.mat,2.fat,每当我输入“1”或“mat”来移除'mat'时,它会显示列表为0.hat 1.fat,我希望它显示0.hat,2.fat)
这是我最近尝试这样做:
string[] stringList = new string[] { "hat", "mat", "fat" };
//Creating list
List<string> list = new List<string>(stringList);
string answer;
//ordering list backwards Z-A
list.Sort((a, b) => -1 * a.CompareTo(b));
//loop to allow them to continue removing items
while (true)
{
//Displaying list to console
for (int i = 0; i < list.Count; i++)
{
//display list
Console.WriteLine("{0}.{1}", i, list[i]);
}
//This is blank
Console.WriteLine();
//instructions what to do
Console.WriteLine("Choose from the list to remove an item: ");
//this will store the users input
answer = Console.ReadLine();
answer = answer.ToLower();
-- this is where I put the removing at --
//Making sure user does not crash program
if (!string.IsNullOrEmpty(answer))
{
var index = list.FindIndex(i => i == answer);
foreach (var item in list)
{
if (index >= 0)
{
list.RemoveAt(index);
}
}
}
我这里使用的不会删除任何东西的方法。 我很难理解。 如果有人能提供一些很好的见解。谢谢
btw,在C#中的评论不包含在双折线像你在这里。他们从//开始或者被封闭为:/ *这里有一些注释*/ –
是的,我知道那部分不在我原来的代码中。 – Pandda