3

Say, I have 3 lists

List<int> l1
List<int> l1,l2,l3

All the 3 lists has many items I want to add all of them to a single list

List<int> finalList
finalList.AddRange(l1) , similarly for l2 and l3.

While doing finalList.AddRange does it copy over items from l1,l2,l3 or does it just refer to those items? If it copies I want to avoid AddRange to save memory as the lists are big.

Rob
  • 26,989
  • 16
  • 82
  • 98
PickUpTruck
  • 63
  • 1
  • 5
  • 3
    You're using an integer, so the values are copied. Even if it merely copied a *reference* to the original integer, the reference itself would use up space. – Rob Feb 02 '17 at 01:07
  • if it is not an int and a class say Employee, do you say that it will not copy the data and make only a ref. I am concern about my memory usages that is why I raised this question and want to avoid adding to the finalList if it copies data. ( reduces memory usage by half ). Thanks for helping me. – PickUpTruck Feb 02 '17 at 17:57

1 Answers1

0

If you want the references to be copied not the data wrap your lists of integers into a class like the following :

    public class ItemsList
    {
        public List<int> ListOfInts {get; set;}

        public ItemsList()
        {
            ListOfInts = new List<int>();
        }
    }

then add them like the following :

        ItemsList l1 = new ItemsList();
        l1.ListOfInts = new List<int> { 1, 2, 3, 4, 5, 6 };//or whatever data inside

        //same for l2, l3

        List<ItemsList> finalList = new List<ItemsList>();
        finalList.Add(l1);//Your adding references to ItemsList class 

Hope this was useful.

Ali Ezzat Odeh
  • 2,093
  • 1
  • 17
  • 17