项目另一个列表复制列表 [英] Copy list of items to another list
问题描述
我想要的项目列表,从list1的复制到另一个目录列表2。我能做到这一点。不过,我不希望在列表2砥所作的更改反映在list1的。
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()));
当然你不需要这种方法。你可以做到这一点也即时在LINQ查询:
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)));
或 List.ConvertAll
:
List<MyClass> list2 = list1.ConvertAll(x => new MyClass(x));
这篇关于项目另一个列表复制列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!