0

I've been trying to add a list to a dictionary<int, struct arts>.

When I add it, then clear the list like list.clear(); then the

Information that I have copied in a dictionary is all cleared as well.

How can I fix this, please?

for (int i = 0; i < current_artslist1.Count; i++)//
                {
                    cnt++;
                    tmp_list1.Add(current_artslist1[i]);
                    if (cnt == limit)
                    {
                        art_small_page++;
                        cnt = 0;       
                        artdict_small_tmp.Add(art_small_page, tmp_list1);
                        tmp_list1.Clear();
                    }                    
                }
NubyShark
  • 143
  • 2
  • 11

1 Answers1

1

The problem is:

artdict_small_tmp.Add(art_small_page, tmp_list1);

does not add the 'items' from the list. It add a reference to tmp_list1, which you are then clearing. So the reference to that list is pointing to the cleared list.

Use .ToList() to take a copy of the items in a list and put them in a new list:

artdict_small_tmp.Add(art_small_page, tmp_list1.ToList());

This adds a new list with the items from tmp_list1, not a reference to tmp_list1.

Now, when you clear tmp_list1, the new list created in the above line will remain untouched.

Neil W
  • 7,670
  • 3
  • 28
  • 41