将新List对象中的值设置为现有List中的值

时间:2017-10-24 01:32:06

标签: c# .net

我尝试使用其他列表中的值填充一个列表中的字段。我在查找如何避免新列表中的Argument Out of Range异常时遇到问题。我尝试将新列表的大小初始化为myObjectA.Count,但后来读到这实际上不会像数组一样初始化该大小的列表。我有点卡住了,希望得到一些帮助。感谢

 List<objectA> myObjectA  =_GetList(id);
 List<objectB> myObjectB = new List<objectB>();


 for (var i=0; i < myObjectA.Count; i++)
 {
      myObjectB[i].Comments = myObjectA[i].Comments;
 }

2 个答案:

答案 0 :(得分:2)

你可以这样做:

for (var i = 0; i < myObjectA.Count; i++)
{
      myObjectB.Add(new objectB()
      {
           Comments = myObjectA[i].Comments
      });
}

这样,每次迭代都会将新的objectB添加到myObjectB列表中。

使用Linq,您可以缩短代码:

myObjectB = myObjectA.Select(x => new objectB { Comments = x.Comments }).ToList();

答案 1 :(得分:2)

因为myObjectB空列表。您正在循环遍历myObjectA列表,该列表可能还有一个项目,并且在循环的第一次迭代中,它将尝试执行类似

的代码
myObjectB[0].Comments = myObjectA[0].Comments;

哪个会崩溃,因为myObjectB列表中没有项目,并且您正在尝试访问第一个项目(第0个索引),因此超出范围异常!特别是指数超出了范围。必须是非负数且小于集合的大小。例外

假设objectBobjectA都具有相同类型的Comments属性,您可以遍历myObjectA列表,并为每个项目创建一个新的{{1}使用objectB方法将对象添加到列表中(最初将其作为空列表初始化)。

Add

上述foreach代码可以使用LINQ投影

制作一个衬里
List<objectB> myObjectB = new List<objectB>();
for (var i=0; i < myObjectA.Count; i++)
{
    var b = new objectB();  //create the object
    b.Comments = myObjectA[i].Comments;  // map the property values
    myObjectB.Add(b);  //add the object to the list
}

变量var bList = myObjectA.Select(x => new objectB { Comments = x.Comments }).ToList(); 将是bList个对象的列表。