当前代码正在编译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);
}
}
}
答案 0 :(得分:3)
这应该可以解决问题:
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
添加项目时提醒用户并阅读其答案。
答案 1 :(得分:0)
尝试使用以下代码:
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);