gpt4 book ai didi

c# - 如何将重复键添加到字典中

转载 作者:IT王子 更新时间:2023-10-29 04:29:17 26 4
gpt4 key购买 nike

我有一些来自文本文件的行,我想添加到字典中。我是第一次使用字典。在添加起始行时它没问题,但突然出现错误:

An item with the same key has already been added

我的代码中有重复的键,我无法更改。这是我的 c# 代码

Dictionary<string, string> previousLines = new Dictionary<string, string> { };
previousLines.Add(dialedno, line);

这里 dialedno 是键,line 是文本文件行。这是我根据键从中检索给定行的代码。

string tansferOrginExt = previousLines[dialedno];

所以我关心的是如何在可能的情况下允许在字典中添加重复的键,如果不允许我如何获得类似的功能。

最佳答案

how to allow to add duplicate keys in Dictionary

这是不可能的。所有键都应该是唯一的。作为 Dictionary<TKey, TValue> 实现:

Every key in aDictionary<TKey, TValue> must be unique according to the dictionary's equality comparer.

可能的解决方案 - 您可以将字符串集合保留为值(即使用 Dictionary<string, List<string>> ),或者(更好)您可以使用 Lookup<TKey, TValue> 而不是字典。


how to check for duplicate keys and delete previous value from Dictionary?

您可以使用 previousLines.ContainsKey(dialedno) 检查 key 是否存在但是如果你总是想保留最后一行,那么只需替换任何字典中的键,或者如果它不在字典中则添加新键:

previousLines[dialedno] = line;

关于c# - 如何将重复键添加到字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22297393/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com