如何在字典中添加重复键 [英] How to add duplicate keys into the Dictionary

查看:629
本文介绍了如何在字典中添加重复键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些文本文件中的行要添加到Dictionary中.我是第一次使用Dictionary.在添加起始行的同时还可以,但突然我出现了错误:

I have some lines from text files that i want to add into the Dictionary.I am using Dictionary for the first time.While adding up starting lines it was Ok but suddenly i got error:

具有相同键的项目已添加

An item with the same key has already been added

在我的代码中有重复的键,我无法更改.这是我在C#中的代码

Here in my code there are duplicate keys which i can not change.Here is my code in c#

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

在此,Dialedno是键,line是文本文件行. 这是我根据密钥从中检索给定行的代码.

Here dialedno is the key and line is the textfile line. Here is the code from which i am retrieving the given line based on key.

string tansferOrginExt = previousLines[dialedno];

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

So my concern is how to allow to add duplicate keys in Dictionary if possible and if not how can i get similar functionality.

推荐答案

如何允许在字典中添加重复键

how to allow to add duplicate keys in Dictionary

不可能.所有键都应该是唯一的.当 Dictionary<TKey, TValue> 实施时:

It is not possible. All keys should be unique. As Dictionary<TKey, TValue> implemented:

Dictionary<TKey, TValue>中的每个键必须是唯一的,具体取决于 字典的相等比较器.

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

可能的解决方案-您可以将字符串集合作为值保留(即使用Dictionary<string, List<string>>),或者(更好)可以使用

Possible solutions - you can keep collection of strings as value (i.e. use Dictionary<string, List<string>>), or (better) you can use Lookup<TKey, TValue> instead of dictionary.

如何检查重复的键以及如何从中删除先前的值 字典?

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

您可以使用previousLines.ContainsKey(dialedno)检查该键是否存在,但是如果您始终要保留最后一行,则只需替换该键具有的任何字典,或者如果字典中没有该键,则添加新键:

You can check if the key exists with previousLines.ContainsKey(dialedno) but if you always want to hold the last line, then just replace whatever dictionary had for the key, or add the new key if it is not in the dictionary:

previousLines[dialedno] = line;

这篇关于如何在字典中添加重复键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆