字典中每个键的添加将覆盖值

本文关键字:添加 覆盖 字典 | 更新日期: 2023-09-27 18:18:41

public Dictionary<string, List<int>> GetAllMemberIDsWithinATable()
{
    List<string> _sectionDataList = this.GetSectionInfo();
    var dict = new Dictionary<string, List<int>>();
    List<int> _memberIds = new List<int>();
    string _staadName = "";
    int iVal = 0;
    bool isEnd = false;
    for (int iSecList = 0; iSecList < _sectionDataList.Count(); iSecList++)
    {
        while ((iSecList < _sectionDataList.Count()) && 
               (!_sectionDataList[iSecList].Equals("TABLE")))
        {
            string data = _sectionDataList[iSecList];
            if (!(data.Equals("TO") || (data.Equals("-"))))
            {
                if (data.Equals("SP") || data.Equals("0.01"))
                {
                    isEnd = true;
                    break;
                }
                else if (!_memberIds.Contains(Convert.ToInt32(data)))
                    _memberIds.Add(Convert.ToInt32(data));
            }                    
            else
            {
                int jData = Convert.ToInt32(_sectionDataList[iSecList + 1]);
                if (iSecList != 0)
                    iVal = iSecList - 1;
                int xData = Convert.ToInt32(_sectionDataList[iVal]);
                for (int i = xData; i <= jData; i++)
                    if (!_memberIds.Contains(i))
                        _memberIds.Add(i);
            }
            iSecList++;
        }
        if (iSecList != _sectionDataList.Count()) 
        {
            if (!isEnd)
            {
                iSecList = iSecList + 2;
                _staadName = _sectionDataList[iSecList];
                this.staadName = _staadName;
                dict.Add(_staadName, _memberIds);
                _memberIds.Clear();
            }
        }
    }
    return dict;
}

_memberIds被替换,而新的密钥即_staadname被添加。就像我想有TUB1501506,ISMC250等作为我的钥匙,从文件中获取它们,并从

memberIds中存储数据

"43至62 71 72 82 92 101至105 110至112 137至146 156 157 168 171 173 -174 185至188 197 198 218 220至222 240 241 244 256 272 274 275 -280至282 285至290 294表st管150150663至69 73至77 79至81 83至87 89至91 93至100 108至109 113至117 -119至136 189至195 206 209至215 217 223 225至239 245 253 264 278 291 -293 297表为ismc2501 ~ 47 ~ 22 25 ~ 28 31 ~ 42 147 ~ 155 158 ~ 166 175 ~ 183 292 -299 TABLE FR ISMC200 SP 0.01 "

正如您所看到的模式,最后一个字符串是_staadname,字符串之前给出的范围是该名称的memberIds列表。

字典中每个键的添加将覆盖值

这仅仅是因为您只有一个_memberIds实例。您永远不会在循环中重新实例化它。因此,for循环的每次迭代都会重用列表。

尝试将其移动到循环中:

// not here
for (int iSecList = 0; iSecList < _sectionDataList.Count(); iSecList++)
{
    // put it here
    List<int> _memberIds = new List<int>();
    // your original code
}