Need to remove duplicate values from C# program

前端 未结 5 1660
南方客
南方客 2020-12-22 07:49

I need some help with a C# program that i am creating. So in this scenario i am inputting duplicate values into the program. For Example, a,b,b,c,c.
The exercise is that

5条回答
  •  青春惊慌失措
    2020-12-22 08:03

    Keep it simple, and although a HashSet is nice semantically, it's not needed for 5 elements (it's actually slower than a List in that case). Worse, it requires a parallel structure to track the characters (assuming you care about order).

    Clearly none of these considerations matter for such a small example but it's good to learn them up front and don't always jump to big-O notation when actually measured performance and memory consumption should be your guide for most practical applications.

    Instead you can simply do:-

    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);
    }
    

    Plus whatever error messages you want to add.

提交回复
热议问题