gpt4 book ai didi

c# - 在字符串列表中查找 Id

转载 作者:太空宇宙 更新时间:2023-11-03 20:51:25 24 4
gpt4 key购买 nike

我是编程新手。我正在制作一份杂货店购物 list 。我有一个字符串列表,用户可以在其中添加杂货:

List<string> list = new List<string>();

现在,如果用户想要删除列表中的某个对象(杂货店),我希望他用数字来完成,而不是在控制台窗口中输入杂货店名称,我已经在这里完成了:

case 2:
Console.WriteLine("What would you like to remove from the list?");
int removeGroc = Convert.ToInt32(Console.ReadLine());
list.RemoveAt(removeGroc);
break;

我想做的是确保检查用户是否输入了例如数字 5 但列表中只有 3 个对象,因此将要求用户再次输入数字,因为列表中只有 3 个对象列表(0、1 和 2)。我到处搜索并尝试了不同的方法,但它们似乎不起作用,或者我的知识太糟糕了,无法理解。那么我该怎么做呢?我知道我需要做什么,但我不知道该怎么做。我在想我需要找到列表的“id”,然后检查它是否存在,但我似乎无法在线找到如何执行此操作。

如果有任何其他新手看到这个,这里是由于评论而起作用的编辑:

Console.WriteLine("What would you like to remove from the list?");
var removeGroc = Console.ReadLine();
int removeGrocId;
bool parseSuccess = int.TryParse(removeGroc, out removeGrocId);
if (removeGrocId < list.Count)
list.RemoveAt(removeGrocId);
else
Console.WriteLine("Write a valid number!");

最佳答案

你可以这样做

list.Count; //return the number of the items in the list

所以你用列表中的项目数来验证它:

if(removeGroc > listCount){ //do someting }

关于c# - 在字符串列表中查找 Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54811073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com