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.

有帮助吗?

解决方案

Are you looking for this?

IEnumerable<string> newList = listSelectedItems.ToList();

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top