C# MVC 5 can';在一个列表中循环一个列表?
我有一个XML文档,我正在阅读它来创建一个对象列表,在这个对象的内部是另一个对象列表。我不知道该怎么做的是循环第二个列表 我有一份按年度分组的时事通讯清单。第一个列表是所有年份的列表(例如:2018年、2017年、2016年、2015年),然后年份内是另一个实际时事通讯列表 我可以循环浏览年份列表,但找不到方法循环浏览当年的时事通讯列表 在我看来,我正试图做类似的事情,但没有看到通讯列表C# MVC 5 can';在一个列表中循环一个列表?,c#,asp.net-mvc,C#,Asp.net Mvc,我有一个XML文档,我正在阅读它来创建一个对象列表,在这个对象的内部是另一个对象列表。我不知道该怎么做的是循环第二个列表 我有一份按年度分组的时事通讯清单。第一个列表是所有年份的列表(例如:2018年、2017年、2016年、2015年),然后年份内是另一个实际时事通讯列表 我可以循环浏览年份列表,但找不到方法循环浏览当年的时事通讯列表 在我看来,我正试图做类似的事情,但没有看到通讯列表 @foreach (var year in Model.NewsletterYearList) {
@foreach (var year in Model.NewsletterYearList)
{
foreach (var item in Model.NewsletterYearList.NewsletterList)
{
}
}
这是我的ViewModel:
public class NewsletterViewModel
{
public List<NewsletterYear> NewsletterYearList;
}
public class NewsletterYear
{
public string Year { get; set; }
public List<Newsletter> NewsletterList;
}
公共类时事通讯视图模型
{
公众名单和年鉴;
}
公共课通讯年
{
公共字符串年份{get;set;}
公开名单;
}
这是一个模型的屏幕截图(为了开发目的,我只做了3个月,3年)。
根据您的型号,您的代码应该是:-
@foreach (var year in Model.NewsletterYearList)
{
// we have a year, and year contains all the newsletters for this year
// so lets loop through the newsletters....
foreach (var item in year.NewsletterList)
{
// item is the newsletter...
}
}
根据你的模型结构,你的循环结构应该是这样的
@if(Model != null && Model.NewsletterYearList.Count >0){
foreach(var year in Model.NewsletterYearList.Count){
// Already we had reference of single item of
// Model.NewsletterYearList variable in 'year'
// So directly use variable 'year' in next iteration
foreach(var newsletter in year.NewsletterList){
// Your business logic
}
}
}
foreach(Model.newsletteerlist.newsletteeslist中的var项目)
,您不是想使用foreach(year.newsletteeslist中的var项目)
?不,newsletteerlist是每年所有列表的列表。酒店年份就在这里,所以我知道我要处理的年份。您需要尝试@CamiloTerevinto comment中的代码(这是正确的)Intellisense不显示Model.newsletteYearList.newsletteList。我没有看到我在做什么,这会阻止它看到第二个列表。我看到你已经解决了你的问题,但没有Model.newsletteYearList.newsletteList
给你一个构建错误?很明显,NewsletterList
不是NewsletterYearList
的属性(它是列表中每个元素的属性,而不是列表本身,就像做PeopleList.Age
)。谢谢,看起来这是可行的。从“时事通讯”这个词开始的很多事情让人有点困惑,但在我看了几分钟之后,它就有了意义。明天我会更多地使用它,但这看起来是我需要的。