![](/img/trans.png)
[英]How do I create a copy of a Dictionary<int,List<int>> without affecting the original (C#)?
[英]In C# How do I copy a list to another list in such a way that on modifying the copied list the original list is not modified
我正在尝试使用AddRange或其他方式将列表复制到另一个列表,但是似乎没有任何正常工作。 无论如何尝试,我都会修改复制的列表,它也会修改原始列表。 如果我使用foreach循环进行复制,它是唯一可行的方法。
static void Main(string[] args)
{
var test = new List<Employee>{ new Employee { ID = "101", Name ="ABC1"}, new Employee{ID = "102", Name = "ABC2"}, new Employee{ ID = "103", Name = "ABC3"}};
var tets2 = new List<Employee>(test);
tets2[0].ID = "1-73";
TestMethod(test.ToList());
}
private static void TestMethod(List<Employee> test)
{
var test1 = new List<Employee>(test);
test1.AddRange(test);
//This is the only one that work
foreach(var item in test)
{
var x = new Employee { ID = item.ID, Name = item.Name };
test1.Add(x);
}
test1[0].ID = "104";
}
没有更短的方法吗?
它不是在修改列表,而是在修改列表中的项目。 您可以具有两个或多个列表-每个List<Employee>
都是一个List<Employee>
-并且如果将项目复制到另一个列表或数组,则两个列表中的项目都是相同的项目。
var x = new Employee { ID = "xyz", Name = "Bob" };
var list = new List<Employee>();
list.Add(x);
var array = new Employee[]{x};
var y = x;
y.ID = "abc";
在此示例中,只有一个Employee
实例,但是有四个引用指向该Employee
。
x
是一个参考 list[0]
是另一个 array[0]
y
但是,您指的是一个实例,包括list[0].ID = "new id"
它都是Employee
的相同实例。
要创建副本,您可以执行以下操作-这是一个冗长的示例,不一定是您想要实际实现的方式:
var newList = new List<Employee>();
foreach(var employee in sourceList) //the list you want to copy from
{
newList.Add(new Employee{ID=employee.ID, Name=employee.Name});
}
添加到newList
的项目不是sourceList
的相同对象。 它们是具有相同属性的新对象。
如果您认为需要经常执行此操作,则可以使Employee
实现ICloneable
。
public class Employee : ICloneable
{
public string ID {get;set;}
public string Name {get;set;}
public object Clone()
{
return new Employee{ID=ID, Name=Name};
}
}
或者,因为属性只是值类型,您可以执行此操作,将属性从源对象复制到新对象中。
public class Employee : ICloneable
{
public string ID {get;set;}
public string Name {get;set;}
public object Clone()
{
return this.MemberwiseClone();
}
}
然后,要创建一个新列表,您可以创建一个扩展方法:
public static class EmployeeExtensions
{
public static List<Employee> ToClonedList(this IEnumerable<Employee> source)
{
return source.Select(employee => employee.Clone() as Employee).ToList();
}
}
然后,您可以像这样从IEnumerable
任何雇员集中创建一个克隆列表:
var myClonedList = oldList.ToClonedList();
(吹毛求疵,你没有实现ICloneable
。你可以只写一个方法是复制的对象。 ICloneable
仅仅是一个约定,让别人知道他们可以调用.Clone()
并创建一个克隆的对象。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.