c# foreach语句没有正确地向模型列表中添加模型

本文关键字:模型 列表 添加 正确地 foreach 语句 | 更新日期: 2023-09-27 18:01:40

我有两个foreach循环,它们在我的应用程序中构建事件的时间轴。我有一个时间轴列表对象,它是时间轴细节对象的列表。代码看起来像这样:

var viewModel = new TimeLineListViewModel();
var timelineDetailsViewModel = new TimelineDetailsViewModel();
var referralDiaryEvents = _referralService.GetReferralDiaryEventsByReferralId((int)referralId).ToList();
var referral = _referralService.GetReferral((int)referralId);
foreach (var referralDiaryEvent in referralDiaryEvents)
{
1    timelineDetailsViewModel.EventDate = referralDiaryEvent.App_DiaryEvent.EventDateTimeScheduled;
2    timelineDetailsViewModel.EventType = referralDiaryEvent.App_DiaryEvent.Ref_EventType.Description;
3    timelineDetailsViewModel.EventDescription = referralDiaryEvent.App_DiaryEvent.EventName;
4    viewModel.TimeLineList.Add(timelineDetailsViewModel);
}
foreach (var referralStatusHistory in referral.App_ReferralStatusHistory)
{
    timelineDetailsViewModel.EventDate = referralStatusHistory.DateChanged;
    timelineDetailsViewModel.EventType = "Referral Status Changed: " + referralStatusHistory.Ref_ReferralStatus.Description;
    timelineDetailsViewModel.EventDescription = referralStatusHistory.Ref_ReferralStatusReason.Description;
    viewModel.TimeLineList.Add(timelineDetailsViewModel);
 }

这一切都应该是直接的,并且应该在每个循环中添加每个项目以构建对象列表。问题是它没有这样做。我实际上不知道它在做什么——当我调试和运行循环时,它做了一些非常奇怪的事情。我对循环中的代码行进行了编号,以供参考。它将运行第一行,然后运行第2行,然后返回到第1行,然后到第3行,然后返回到第2行,然后到第4行,以此类推,它在循环中毫无理由地来回跳跃,而不是一行接一行地直接运行。

最后它会将timelineDetailsViewModel添加到TimeLineList中。然后它会为下一个项目再次开始循环,但是当它再次将timelineDetailsViewModel添加到TimeLineList时,TimeLineList计数变为0,然后跳转到第2行,然后再次返回到4,然后将项目添加到列表中,但覆盖之前添加到列表中的每个项目,以便列表中的所有timelineDetailsViewModel项目与最新添加的项目相同。所以当它到达第二个foreach循环的底部时,在我的代码中应该有七个唯一的timelineDetailsViewModel项目在列表中,所有的细节都不同-最终有七个项目,但它们都与最后一个timelineDetailsViewModel相同,在第二个foreach循环的最后一个循环中添加。

有人知道这里发生了什么吗?我的视觉工作室坏了吗?我试过重启我的电脑,但没有效果。我用的是visual studio 2012

c# foreach语句没有正确地向模型列表中添加模型

它没有解释奇怪的调试器行为,但实际上您的代码中有另一个错误:

只创建一次TimeLineListViewModelTimelineDetailsViewModel的实例。然后,通过foreach循环迭代,您总是更改完全相同实例的属性

在每次循环中,你都要改变的属性,这是你创建的唯一一个实例,并尝试将这个实例添加到你的列表中x次。

您需要在您的foreach循环中创建实例s:

foreach (var referralDiaryEvent in referralDiaryEvents)
{
    // create a NEW instance for every event!
    var timelineDetailsViewModel = new TimelineDetailsViewModel();
    timelineDetailsViewModel.EventDate = referralDiaryEvent.App_DiaryEvent.EventDateTimeScheduled;
    timelineDetailsViewModel.EventType = referralDiaryEvent.App_DiaryEvent.Ref_EventType.Description;
    timelineDetailsViewModel.EventDescription = referralDiaryEvent.App_DiaryEvent.EventName;
    viewModel.TimeLineList.Add(timelineDetailsViewModel);
}