我正在创建一个字典,它有一个键作为字典.这是两个词典的声明.
Dictionary<Dictionary<Int64,string>, Int64> AccountTypeDic = new Dictionary<Dictionary<Int64, string>, Int64>();
Dictionary<Int64,string> IdName = new Dictionary<Int64,string>();
Run Code Online (Sandbox Code Playgroud)
现在,当我尝试将数据添加到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()));
}
}
Run Code Online (Sandbox Code Playgroud)
sqlDataReader具有所有字段ID,帐户名和序列码.
请不要建议我应该使用其他一些数据结构.我只是想知道如何以这种方式处理它.
看起来你试图在这里一遍又一遍地添加相同的密钥:
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()));
}
Run Code Online (Sandbox Code Playgroud)
你的IdName实例总是一样的.因此,请确保您将不同的实例作为键.基本上IdName应该在while循环中声明和实例化字典:
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);
}
Run Code Online (Sandbox Code Playgroud)
请不要建议我应该使用其他一些数据结构.
当我们看到这件事时,这正是每个人都会建议你的.我见过人们使用字典作为值,但字典作为另一个字典的键,哦.
| 归档时间: |
|
| 查看次数: |
368 次 |
| 最近记录: |