vivek jain
vivek jain

Reputation: 591

Dictionary within Dictionary in C#

I am creating A Dictionary which has a key as 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.

Execption: An item with the same key has already been added. So please tell me how should I add data into 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.

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.

Upvotes: 1

Views: 1354

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

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. So make sure you have different instances as keys. Basically the IdName dictionary should be declared and instantiated inside your while loop:

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.

Upvotes: 7

Related Questions