如果键存在,则将数组值追加到字典中

时间:2019-08-03 09:06:21

标签: c# arrays dictionary

我正在尝试创建一个dictionary<string,DocValueModelClass>,其中DocValueModelClass是一个几乎没有数组组件的模型类。

因此,当字典中存在键时,我想将数组值附加到该键所在的字典中。当我尝试添加该值时,它将作为一个类附加整个值,覆盖模型类DocValueModelClass中的所有数据,最后以字典中数组中的值结尾。

if (data.Length == 5)
{
    docValueModelClass.type = ConfigurationManager.AppSettings["type"];
    docValueModelClass.destinationValue = new string[] { data[0] };
    docValueModelClass.sourceKey = new string[] { data[1] };
    docValueModelClass._name = data[2];
    docValueModelClass.description = data[3];
    docValueModelClass.title = data[2];

    if (jsonDictionary.ContainsKey(data[4]))
    {
        jsonDictionary[data[4]] = docValueModelClass;
    }
    else
    {
        jsonDictionary.Add(data[4], docValueModelClass);
    }
}

我只想将数组值附加到docValueModelClass.destinationValuedocValueModelClass.sourceKey(如果键存在并且不会覆盖)。请提出如何实现这一目标的建议。试图在线检查,但找不到任何解决方法。

1 个答案:

答案 0 :(得分:0)

解决方案:

如果存在字典对象,则仅应修改其属性,而不能通过创建新对象来修改整个对象。

if (jsonDictionary.ContainsKey (data[4])) {
  // Updates only the property of existing object
  jsonDictionary[data[4]].destinationValue = new string[] { data[0] };
  jsonDictionary[data[4]].sourceKey = new string[] { data[1] };
} else {
  docValueModelClass = new DocValueModelClass ();
  docValueModelClass.type = ConfigurationManager.AppSettings["type"];
  docValueModelClass.destinationValue = new string[] { data[0] };
  docValueModelClass.sourceKey = new string[] { data[1] };
  docValueModelClass._name = data[2];
  docValueModelClass.description = data[3];
  docValueModelClass.title = data[2];
  // Adds the new object
  jsonDictionary.Add (data[4], docValueModelClass);
}