简体   繁体   English

C#词典中的词典

[英]Dictionary within Dictionary in C#

I am creating A Dictionary which has a key as Dictionary. 我正在创建一个词典,其关键字为Dictionary。 Here is the declaration of both dictionaries. 这是两个词典的声明。

Dictionary<Dictionary<Int64,string>, Int64> AccountTypeDic = new Dictionary<Dictionary<Int64, string>, Int64>();
Dictionary<Int64,string> IdName = new Dictionary<Int64,string>(); 

Now when I'm trying to add data into Dictionary I'm getting exception. 现在,当我尝试将数据添加到Dictionary时,出现异常。

Execption: An item with the same key has already been added. 执行:已经添加了具有相同键的项目。 So please tell me how should I add data into Dictionary. 因此,请告诉我如何将数据添加到Dictionary中。

if (sqlDataReader.HasRows)
{
    while (sqlDataReader.Read())
    {
        IdName.Clear();
        IdName.Add(Int64.Parse(sqlDataReader["ID"].ToString()), 
           sqlDataReader["ACCOUNT_NAME"].ToString());
        AccountTypeDic.Add(IdName,
           Int64.Parse(sqlDataReader["SEQUENCE_ID"].ToString()));
    }
}

sqlDataReader has all the fields ID, Account Name and Sequence Code. sqlDataReader具有所有字段ID,帐户名和序列号。

Please don't suggest me that I should use some other data structures. 请不要建议我使用其他一些数据结构。 I just want to know how it can be handled in this way. 我只想知道如何以这种方式处理它。

Looks like you are attempting to add the same key over and over again here: 您似乎在这里尝试一遍又一遍地添加相同的键:

while (sqlDataReader.Read())
{
    IdName.Clear();
    IdName.Add(Int64.Parse(sqlDataReader["ID"].ToString()),sqlDataReader["ACCOUNT_NAME"].ToString());
    AccountTypeDic.Add(IdName, Int64.Parse(sqlDataReader["SEQUENCE_ID"].ToString()));
}

Your IdName instance is ALWAYS the same. 您的IdName实例始终相同。 So make sure you have different instances as keys. 因此,请确保您具有不同的实例作为键。 Basically the IdName dictionary should be declared and instantiated inside your while loop: 基本上,应该在while循环内声明并实例化IdName字典:

while (sqlDataReader.Read())
{
    long id = sqlDataReader.GetInt64(sqlDataReader.GetOrdinal("ID"));
    string accountName = sqlDataReader.GetString(sqlDataReader.GetOrdinal("ACCOUNT_NAME"));
    long sequenceId = sqlDataReader.GetInt64(sqlDataReader.GetOrdinal("SEQUENCE_ID"));

    var idName = new Dictionary<long, string>();
    idName.Add(id, accountName);

    // Make sure that here you don't have repetitions of idName
    // or the next line will bomb with the exact same exception
    AccountTypeDic.Add(idName, sequenceId);
}

Please don't suggest me that I should use some other data structures. 请不要建议我使用其他一些数据结构。

That's exactly what everybody will suggest you when we see this thing . 正是当我们看到这个东西时,每个人都会向您建议。 I have seen people using dictionaries as values, but dictionaries as keys for another dictionary, oh well. 我见过人们使用字典作为值,但使用字典作为另一本字典的键,哦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM