英文:
how to add elements to a list without the VyRef problem
问题
我希望列表的每次迭代都能存储新的值。
英文:
I am creating a list of objects but every time I add a new element to the list, it modifies the previous elements.
private List<DocRequisicionTransferModel> sendReqMultiple(DocRequisicionTransferModel docRequisicionTransferModel)
{
List<DocRequisicionTransferModel> data = new List<DocRequisicionTransferModel>();
//doctoReqTransfer.MovimientoRequisicionTransferencia = docRequisicionTransferModel.MovimientoRequisicionTransferencia;
List<MovRequisicionTransferModel> movRequisicionTransferModels = new List<MovRequisicionTransferModel>();
movRequisicionTransferModels = docRequisicionTransferModel.MovimientoRequisicionTransferencia;
List<String> distinctBodegas = docRequisicionTransferModel.MovimientoRequisicionTransferencia.Select(movto => movto.IdBodegaSal).Distinct().ToList();
foreach (String bodega in distinctBodegas)
{
if (!String.IsNullOrEmpty(bodega))
{
DocRequisicionTransferModel doctoReqTransfer = new DocRequisicionTransferModel();
doctoReqTransfer = docRequisicionTransferModel;
doctoReqTransfer.IdBodegaSal = bodega;
doctoReqTransfer.MovimientoRequisicionTransferencia = movRequisicionTransferModels.Where(movto => movto.IdBodegaSal.Equals(bodega)).ToList();
data.Add(doctoReqTransfer);
}
}
return data;
I expect each iteration of the list to store new values
答案1
得分: 0
你的代码中没有隐藏的问题。只是你犯了逻辑错误:
DocRequisicionTransferModel doctoReqTransfer = new DocRequisicionTransferModel(); // 创建了一个新对象,但doctoReqTransfer的值会在后续被覆盖
doctoReqTransfer = docRequisicionTransferModel; // 在每次迭代中,你在这里分配了相同的值
如果你需要创建新的doctoReqTransfer,并将其从docRequisicionTransferModel复制过来,可以在DocRequisicionTransferModel类中添加复制构造函数。
英文:
There is no hidden problem behind your code. Just you made the logical error:
DocRequisicionTransferModel doctoReqTransfer = new DocRequisicionTransferModel(); // new object is created, but the value of doctoReqTransfer overwrites further
doctoReqTransfer = docRequisicionTransferModel; // here you assign the same value in each iteration
If you need to create the new doctoReqTransfer copying it from docRequisicionTransferModel, add the copying constructor to the DocRequisicionTransferModel class.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论