C#中Distinct函数未生效,重复元素未被去除求助
C#数组处理程序中Distinct函数未生效的问题修复
你的代码核心问题是命令读取逻辑错误,导致Distinct命令根本没被执行:
- 在进入
while循环前,你已经通过string text = Console.ReadLine();读取了输入的Distinct命令,但进入循环后第一行就执行text = Console.ReadLine();,直接将text替换为下一行的End,跳过了Distinct的判断分支。
修复后的完整代码
using System; using System.Collections.Generic; using System.Linq; namespace Array.Processing { class Program { static void Main(string[] args) { string input = Console.ReadLine(); List<string> texts = input.Split(" ").ToList(); string text; int a = 0; // 循环条件中直接读取输入,确保所有命令都被处理 while ((text = Console.ReadLine()) != "END") { List<string> infos = text.Split(" ").ToList(); if (text == "Distinct") { texts = texts.Distinct().ToList(); } if (text == "Reverse") { texts.Reverse(); } if (infos[0] == "Replace") { // 使用TryParse避免非数字索引引发异常 if (int.TryParse(infos[1], out int index) && index >= 0 && index < texts.Count) { texts.RemoveAt(index); texts.Insert(index, infos[2]); } else { a++; } } } for(int n = 0; n < a; n++) { Console.WriteLine("Invalid input!"); } foreach (string info in texts) { Console.Write(info + " "); } } } }
关键修复点
- 调整命令读取逻辑:将
text的读取移到while循环条件中,确保每一行输入的命令都会被处理,不会出现遗漏。 - 异常安全优化:把
int.Parse替换为int.TryParse,避免输入非数字索引时程序崩溃。
修改后执行你的测试输入,输出会变成one two ,Distinct功能正常生效。
内容的提问来源于stack exchange,提问作者Martin Kulev
相关产品推荐
相关产品推荐

