I am trying to copy the list of items from list1 to another list list2. I'm able to do that. However I don't want the changes made in list2 tobe reflected in list1.
class Program
{
static void Main(string[] args)
{
List<MyClass> list1 = new List<MyClass>();
list1.Add(new MyClass(){ID = 1, Name = "name1"});
list1.Add(new MyClass(){ID = 2, Name = "name2"});
list1.Add(new MyClass(){ID = 3, Name = "name3"});
//Copy items from list1 to list2
List<MyClass> list2 = new List<MyClass>(list1);
list1.ForEach(x => Console.WriteLine(x.Name)); //It shows the name as added
//Empty items in list2
list2.ForEach(x => x.Name = string.Empty);
//Print items in list1
list1.ForEach(x => Console.WriteLine(x.Name)); //It shows the name is empty
Console.ReadKey();
}
}
class MyClass
{
private int id;
public int ID
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
I hope there should be an easy way.
Since this is a reference type you are changing all. You need to create a copy of that instance:
public class MyClass
{
private int id;
public int ID
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public MyClass Copy()
{
return new MyClass
{
ID = this.ID,
Name = this.Name
};
}
}
Now you can create the second list in this way:
List<MyClass> list2 = new List<MyClass>(list1.Select(x => x.Copy()));
Of course you don't need that method. You could do that also on-the-fly in the LINQ query:
List<MyClass> list2 = new List<MyClass>(list1.Select(x => new MyClass { ID = x.ID, Name = x.Name }));
Another similar approach is a copy-constructor. A copy-constructor is used to initialize an instance by providing another instance of the same type:
public class MyClass
{
private int id;
public MyClass(MyClass instance)
{
this.id = instance.ID;
this.name = instance.Name;
}
public int ID
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
Now you could fill the list with copies in this way:
List<MyClass> list2 = new List<MyClass>(list1.Select(x => new MyClass(x)));
or with List.ConvertAll
:
List<MyClass> list2 = list1.ConvertAll(x => new MyClass(x));
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments