使用Dictionary时获取KeyNotFoundException

时间:2016-11-22 11:55:05

标签: c#

我正在使用Dictionary

private Dictionary<int, List<SpawnGroup>> spawnsByMapId 
             = new Dictionary<int, List<SpawnGroup>>();

但是在使用此代码时出现错误'KeyNotFoundException':

List<SpawnGroup> a = spawnsByMapId[worldId];//KeyNotFoundException
if (a == null)
{
     // do something with a
}

我想要字典spawnsByMapId[worldId]添加到List<SpawnGroup>,但如果spawnsByMapId[worldId]的密钥不存在,则return null进入List<SpawnGroup>

那么我需要做什么?

2 个答案:

答案 0 :(得分:4)

使用ContainsKey和三元运算符:

List<SpawnGroup> a = spawnByMapId.ContainsKey(worldId) ? spawnsByMapId[worldId] : null;
if(a != null)
{
     // a is not null here.
}

TryGetValue

List<SpawnGroup> a = null;
if(spawnsByMapId.TryGetValue(worldId, out a))
{
    // a is not null here.
}

听起来(来自评论)就像您尝试这样做:

List<SpawnGroup> a = null;
if(!spawnsByMapId.TryGetValue(worldId, out a))
{
    // add new record to spawnsByMapId
    spawnsByMapId.Add(worldId, new List<SpawnGroup>());
}

答案 1 :(得分:0)

我的标准模式如果您想使用嵌套字典,请执行以下操作:

Called from: SubClass1
other_arg1: -3, other_arg2: [-1;-2]

Called from: SubClass2
other_arg1: 3, other_arg2: [1;2]