需要从C#程序中删除重复值

我需要一些我正在创建的C#程序的帮助。 所以在这种情况下,我将重复的值输入到程序中。 例如,a,b,b,c,c。
练习是,如果输入任何重复的字母(没有数字),我应该收到一个错误,说明“重复值。请再试一次!” 并且不接受重复值,并应将值显示为a,b,c,d,e。

class Program { static void Main(string[] args) { char[] arr = new char[5]; //User input Console.WriteLine("Please Enter 5 Letters only: "); for (int i = 0; i < arr.Length; i++) { arr[i] = Convert.ToChar(Console.ReadLine()); } //display for(int i = 0; i<arr.Length; i++) { Console.WriteLine("You have entered the following inputs: "); Console.WriteLine(arrArray[i]); } } } 

因为操作主要是查找和插入,所以在开始时选择正确的数据结构,使用HashSet而不是数组。

使用哈希表(通用字典)是确定是否已经遇到输入字符的有效方法。

此外,.NET框架中的Char.IsLetter方法是检查错误数据的好方法。

 static void Main(string[] args) { Dictionary charsEntered = new Dictionary(); Console.WriteLine("Please enter 5 characters, each on a separate line."); while (charsEntered.Count() < 5) { Console.WriteLine("Enter a character:"); char[] resultChars = Console.ReadLine().ToCharArray(); if(resultChars.Length != 1 || !Char.IsLetter(resultChars[0])) { Console.WriteLine("Bad Entry. Try again."); } else { char charEntered = resultChars[0]; if (charsEntered.ContainsKey(charEntered)) Console.WriteLine("Character already encountered. Try again."); else charsEntered[charEntered] = true; } } Console.WriteLine("The following inputs were entered:"); Console.WriteLine(String.Join(", ", charsEntered.Keys)); Console.ReadLine(); } 

使用Any linq表达式来validation重复项。 char.TryParse将validation输入并在成功时返回true

 public static void Main() { char[] arr = new char[5]; //User input Console.WriteLine("Please Enter 5 Letters only: "); for (int i = 0; i < arr.Length; i++) { char input; if(char.TryParse(Console.ReadLine(), out input) && !arr.Any(c=>c == input)) { arr[i] = input; } else { Console.WriteLine( "Error : Either invalid input or a duplicate entry."); i--; } } Console.WriteLine("You have entered the following inputs: "); //display for(int i = 0; i 

工作Code

阐述Shelvin使用HashSet的答案

 HashSet chars = new HashSet(); //User input Console.WriteLine("Please Enter 5 Letters only: "); for (int i = 0; i < 5; ) { char c = Convert.ToChar(Console.ReadLine()); if(!("abcdefghijklmnopqrstuvwxyz".Contains(c.ToString().ToLower()))) { Console.WriteLine("Please enter an alphabet"); continue; } else if (!chars.Contains(c)) { chars.Add(c); i++; } else { Console.WriteLine("Duplicate value please try again"); continue; } } //display Console.WriteLine("You have entered the following inputs: "); foreach(char c in chars) Console.WriteLine(c.ToString()); Console.Read(); 

保持简单,虽然HashSet在语义上很好,但5个元素不需要它(在这种情况下它实际上比List慢)。 更糟糕的是,它需要一个并行结构来跟踪角色(假设你关心秩序)。

显然,这些考虑事项对于这样一个小例子都不重要,但是如果实际测量的性能和内存消耗应该是大多数实际应用的指南,那么最好先学习它们并且不要总是跳到big-O表示法。

相反,你可以简单地做: –

 List chars = new List(5); while (chars.Count < 5) { char c = Console.ReadKey().KeyChar; if (!char.IsLetter(c)) continue; if (chars.Contains(char)) continue; chars.Add(char); } 

加上你想要添加的任何错误消息。