Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a shallow copy of an IEnumerable<T>?

I have an IEnumerable object as:

IEnumerable<string> listSelectedItems; 

Which contains three items. Now i created a new object and want to get all items from listSelectedItems, so i wrote this code:

 IEnumerable<string> newList = listSelectedItems;

But now when i alter newList, the listSelectedItems also gets altered. How can i achieve altering or creating a new IEnumerable without refernce.

like image 511
Murtaza Munshi Avatar asked Dec 04 '22 08:12

Murtaza Munshi


2 Answers

Are you looking for this?

IEnumerable<string> newList = listSelectedItems.ToList();
like image 121
Sriram Sakthivel Avatar answered Dec 25 '22 09:12

Sriram Sakthivel


IEnumerable is an interface, so you can't instantiate it, you need an implementation of it, for example List

IEnumerable<string> newList = new List<string>(listSelectedItems);

In your case setting newList = listSelectedItems means that newList will be just a reference to the listSelectedItems so if the underlying object is changed, newList will reference the changed object.

like image 43
VladL Avatar answered Dec 25 '22 09:12

VladL