将元素添加到字典中的列表会产生意外的结果 c#

弗朗切斯科·伊阿皮卡

我正在将后端转换为 c#,我注意到一个奇怪的行为

当我向字典中的列表添加元素时

(实际上在另一本字典中):

很快,它会将值添加到字典中每个元素的每个列表中。

这是代码:

       public class Validator_Counter_Model
        {
            public readonly  Dictionary<string,Info_Model> Info;
            private Dictionary<string,Dictionary<DateTime,List<int>>> _map = new Dictionary<string, Dictionary<DateTime,List<int>>>();
            public Validator_Counter_Model(Dictionary<string, Info_Model> info)
            {
                Info = info;
            }
            public void Add(Validation_Element element)
            {

/// #### PROBLEM IS HERE!
                if (!_map.ContainsKey(element.Id))
                {
                    Dictionary<DateTime, List<int>> newmap = new Dictionary<DateTime, List<int>>();
                    _map.Add(element.Id, newmap);
                }

                DateTime fulldate = new Custom_Time_Model(element.Time).RegularTime;
                if (!_map[element.Id].ContainsKey(fulldate.Date))
                {
                    List<int> newList = new List<int>();
                    _map[element.Id].Add(fulldate.Date, newList);
                }
                _map[element.Id][fulldate.Date].Add(element.Time);
/// #### PROBLEM IS HERE!

            }

            public void Del(Validation_Element element)
            {
                DateTime fulldate = new Custom_Time_Model(element.Time).RegularTime;
                DateTime date = new DateTime(fulldate.Year, fulldate.Month, fulldate.Day);
                _map[element.Id][date].Remove(element.Time);
            }

            public void Update(Dictionary<string, Dictionary<DateTime, List<int>>> newMap) => _map = newMap;

            public Dictionary<string, Dictionary<DateTime, List<int>>> map => _map;

        }
    }
弗朗切斯科·伊阿皮卡

这里找到答案

基本上第二个字​​典(第一个值中的那个)本身不是“字典”,而是另一个字典的引用,这就是为什么向其列表添加值会更改每个键的所有列表的原因

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在我的C ++链表实现中取消引用节点指针会产生意外结果

为什么C中的此函数会产生意外结果?

C ++:在基础对象列表中,派生内存在通过引用传递时会产生意外结果

C#中的时间跨度产生意外结果

For循环在C中产生意外结果

for循环在C中产生意外结果

C#如何将列表添加到字典中

在c#中将键值对列表添加到字典中

我无法将元素添加到列表-C ++

将元素添加到链接列表C

将NSDictionary附加到[NSDictionary]会产生意外结果

C Linux pthread:使用消息队列将数据从一个线程发送到另一个线程会产生意外结果

将元素添加到适当的C ++函数中

将新元素添加到c中的struct数组

crc 将 C 代码转换为 Java 的四个字节产生意外结果

将char添加为int会产生意外结果

将项目添加到列表中C#WPF

将值添加到类 c# 中的列表

C#:将当前实例添加到列表中

将sympy中的值替换为列表会产生意外的结果

c#字典如何将具有单个键的重复值的分隔字符串列表中的数据添加到字典中

使用C#驱动程序将UDT元素添加到Cassandra中的列表集合的正确方法是什么?

C#-将实现接口的对象添加到字典

C#如何最好地将字符串数组的元素添加到通用列表

如何避免将bool属性自动添加到列表的元素(C#)?

在C#中检查VB.NET对象是否为null会产生意外的编译错误

c#xml linq将元素添加到元素

C:将数组的所有元素添加到另一个元素中

将列表添加到列表Linq C#