开发者

How to update some part of the complex dictionary value in C#

My dictionary declared as below

    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
    }

Function InitDataDic Called below, How can I write the code of the dictionary .Remove() and .Add() after reassign tdi.TOTSMP = 0 under true condition in a simply way.

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);
    }
}


You don't have to add/remove from dictionary if you want to update the object (of ref type) in dictionary - just update the object.

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
{
  ....
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜