Is this the only way of passing a List to a method and editing that List, without modifying the original List?
class CopyTest1
{
List<int> _myList = new List<int>();
public CopyTest1(List<int> l)
{
foreach (int num in l)
{
_myList.Add(num);
}
_myList.RemoveAt(0); // no effect on original List
}
}
duplicate the list:
_myLocalList = new List<int>(_myList);
and perform the operations on the local list.
Use AsReadOnly
for this:
class CopyTest1
{
List<int> _myList = new List<int>();
public CopyTest1(IList<int> l)
{
foreach (int num in l)
{
_myList.Add(num);
}
_myList.RemoveAt(0); // no effect on original List
}
}
And call it via CopyTest1(yourList.AsReadOnly())
.
There is another way. You can use the copy constructor of List<T>
:
List<int> _myList;
public CopyTest1(List<int> l)
{
_myList = new List<int>(l);
}
Clone objects in the list to other list and work on this copy
static class Extensions
{
public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable
{
return listToClone.Select(item => (T)item.Clone()).ToList();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With