info-re:stringLists中的add/remove方法
本文关键字:remove 方法 add 中的 stringLists info-re | 更新日期: 2023-09-27 18:28:34
当前代码正在编译O.K,如果发现重复,则会自动删除。用户是否可以选择在删除之前保留重复项。或者有没有其他适合我的方法。
static void Main(string[] args)
{
List<string> dictionaryList = new List<string>();
string input;
Console.Write("Please enter a string or END to finish: ");
input = Console.ReadLine();
while (input.ToUpper() != "END")
{
if (!dictionaryList.Contains(input)) // This is where i am looking of a user response of y/n too add duplicate string
dictionaryList.Add(input);
Console.Write("Please enter a string or END to finish: ");
input = Console.ReadLine();
}
dictionaryList.Sort();
Console.WriteLine("Dictionary Contents:");
foreach (string wordList in dictionaryList)
Console.WriteLine("'t" + wordList);
}
}
}
这应该可以做到:
while (input.ToUpper() != "END")
{
bool blnAdd = true;
if (dictionaryList.Contains(input))
{
Console.Write("Already exists, keep the duplicate? (Y/N)");
blnAdd = Console.ReadLine().Equals("Y");
}
if (blnAdd)
dictionaryList.Add(input);
Console.Write("Please enter a string or END to finish: ");
input = Console.ReadLine();
}
代码背后的逻辑:如果输入已经存在于列表中,则提醒用户并读取他的答案——仅当Y
添加项目时。
尝试使用以下代码:
List<string> dictionaryList = new List<string>();
string input;
Console.Write("Please enter a string or END to finish: ");
input = Console.ReadLine();
while (input.ToUpper() != "END")
{
if (dictionaryList.Contains(input))
{
Console.Write("Do you want to have dup string(Y/N):");
string response = string.Empty;
response = Console.ReadLine();
if (response.ToUpper().Equals("Y"))
dictionaryList.Add(input);
}
else
{
dictionaryList.Add(input);
}
Console.Write("Please enter a string or END to finish: ");
input = Console.ReadLine();
}
dictionaryList.Sort();
Console.WriteLine("Dictionary Contents:");
foreach (string wordList in dictionaryList)
Console.WriteLine("'t" + wordList);