【发布时间】:2016-06-24 16:23:40
【问题描述】:
我正在尝试使用 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";
}
没有更短的方法吗?
【问题讨论】:
-
我相信你可以使用 LINQ:
originalList.ForEach(x => CopiedList.Add(new CopiedListObject { prop = x.prop, prop2 = x.prop2 })