سؤال

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