You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

关键修复点

  1. 调整命令读取逻辑:将text的读取移到while循环条件中,确保每一行输入的命令都会被处理,不会出现遗漏。
  2. 异常安全优化:把int.Parse替换为int.TryParse,避免输入非数字索引时程序崩溃。

修改后执行你的测试输入,输出会变成one two ,Distinct功能正常生效。

内容的提问来源于stack exchange,提问作者Martin Kulev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 03:25:48