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

如何解决C#中将数组存入Dictionary时出现重复值的问题

解决方案

核心问题定位

  • 你把字典初始化、填充、遍历输出的逻辑全部嵌套在了遍历userInputArray的外层for循环中,数组有多少个元素,这段逻辑就会重复执行多少次,最终会输出多遍相同的字典内容,看起来就像出现了重复值。
  • 空值判断逻辑位置错误:你在调用了userInputArray.Length之后才判断数组是否为null,如果数组真的为空,会在调用Length属性时直接抛出空引用异常,根本执行不到判断逻辑。
  • 你当前的字典是以数组索引为Key、数组值为Value,索引本身是全局唯一的,所以哪怕数组里有重复的Value,字典也可以正常插入,不会触发Key重复报错。如果你希望字典里不存在重复的Value,需要额外做去重处理。

修复方案

场景1:保留原始数组全部内容,仅修复重复输出问题

如果你不需要对数组值做去重,只需要正常存储原始数组的索引和对应值,删掉多余的外层for循环即可:

UserInput u = new UserInput();
double[] userInputArray = u.ArrayOfDoublePrecisionFloatingPointValues();

// 空判断提前,避免空引用异常
if (userInputArray == null || userInputArray.Length == 0)
{
    Console.WriteLine("You have entered no values!  Add values");
    return;
}

Dictionary<int, double> indexAndIndexValue = new Dictionary<int, double>();
foreach (var (j, t)  in userInputArray.Enumerate())
{
    indexAndIndexValue.Add(j, t);
}

foreach (var (key, value) in indexAndIndexValue)
{
    Console.WriteLine(key + ":" + value);
    Console.Write("------");
    Console.WriteLine("Count: " + indexAndIndexValue.Count);
}

场景2:需要剔除重复的数组值,仅保留每个值第一次出现的索引

如果你要字典中不存在重复的Value,在填充字典时添加存在性判断即可,不需要修改原始数组:

Dictionary<int, double> indexAndIndexValue = new Dictionary<int, double>();
foreach (var (j, t)  in userInputArray.Enumerate())
{
    // 仅当当前值不存在于字典中时才添加,保留该值第一次出现的原始索引
    if (!indexAndIndexValue.ContainsValue(t))
    {
        indexAndIndexValue.Add(j, t);
    }
}

为什么Distinct()没有生效

你直接对原始数组调用Distinct().ToArray()会生成一个新的去重数组,但是新数组的索引会从0重新计算,和原始数组的索引不匹配,不符合你保留原始索引的需求,所以看起来没有生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:36:03