views:

37

answers:

1

Hello. 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);
    }
}
+1  A: 

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
{
  ....
}
VinayC
@VinayC, It works quite well, Thank you.
Nano HE
Finially, I found another more simply solution as `DataDic[trid].TOTSMP = tdi.TOTSMP` to update the exist dictionary value.
Nano HE