How to copy one list into other list

  • Thread starter Thread starter Swapnil
  • Start date Start date
S

Swapnil

hi,

I want to copy the elements of one list to the other list.
Is there any function to do this operation in C#.

Plz explain with example.
 
Swapnil said:
I want to copy the elements of one list to the other list.
Is there any function to do this operation in C#.

Plz explain with example.

You can use the AddRange method, which accepts any IEnumerable type, such as
another list:

List<Whatever> originalList = new List<Whatever>();
originalList.Add(...); //Load original list
....
List<Whatever> copiedList = new List<Whatever>();
copiedList.AddRange(originalList);
//Now you have another list with a copy of all elements.
Note that if "Whatever" is a reference type, you will have copied the
references to the elements, not the contents of the elements.
 
You can use the AddRange method, which accepts any IEnumerable type, such as
another list:

List<Whatever> originalList = new List<Whatever>();
originalList.Add(...); //Load original list
...
List<Whatever> copiedList = new List<Whatever>();
copiedList.AddRange(originalList);
//Now you have another list with a copy of all elements.
Note that if "Whatever" is a reference type, you will have copied the
references to the elements, not the contents of the elements.

The List<T> constructor is overloaded to take IEnumerable<T>. You can
try this:
Assuming firstList is of List<MyType>,
List<MyType>secondList = new List<MyType>(firstList);
 
The List<T> constructor is overloaded to take IEnumerable<T>. You can
try this:
Assuming firstList is of List<MyType>,
List<MyType>secondList = new List<MyType>(firstList);- Hide quoted text -

- Show quoted text -

Forgot to reiterate Alberto's point- Even though the list instance is
different, the MyType objects in both list are the same i.e
references. So if you change any object in one list it'll be reflected
in the other list also.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top