Search code examples
c#.netlistaddrange

C# List AddRange - does it copy the items of add by reference


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.


Solution

  • 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.