Как обновить некоторую часть значения комплексного словаря в C # - PullRequest
0 голосов
/ 30 августа 2010

Мой словарь объявлен как показано ниже

    public static Dictionary<object, DataInfo> DataDic = new Dictionary<object, DataInfo>(); 

    public class DataInfo
    {
        public string DSPER;       // Data Sample Period
        public int TOTSMP;      // Total Samples to be made
        public int REPGSZ;      // Report Group Size
        public List<int> IDList;   // Array List to collect all the enabled IDs
    }

Функция InitDataDic Вызывается ниже, Как я могу написать код словаря .Remove() и .Add() после переназначения tdi.TOTSMP = 0 в true состояние просто.

public void InitDataDic (object objid, DataInfo datainfo, int totsmp)
{
    DataInfo tdi = new DataInfo(); 
    object trid = objid;
    tdi = datainfo; 

    if (DataDic.ContainsKey(trid) == true)
    {
        DataDic.Remove(trid);  // here, i mentioned above
        tdi.TOTSMP = 0;
        DataDic.Add(trid, tdi);  // here, i mentioned above
    }
    else
    {
        tdi.TOTSMP = topsmp;  
        DataDic.Add(trid, tdi);
    }
}

1 Ответ

1 голос
/ 30 августа 2010

Вам не нужно добавлять / удалять из словаря, если вы хотите обновить объект (типа ref) в словаре - просто обновите объект.

if (DataDic.TryGetValue(trid, out tdi)
{
   // already exists in dict, tdi will be initialized with ref to object from dict
   tdi.TOTSMP = 0;   // update tdi
}
else
{
  ....
}
...