C# 如何在MVC4中向列表添加值?
我将模型定义为:C# 如何在MVC4中向列表添加值?,c#,asp.net-mvc-4,for-loop,C#,Asp.net Mvc 4,For Loop,我将模型定义为: public class CMBCategory { public int ID { get; set; } public string Name { get; set; } public List<CMBCategory> children = new List<CMBCategory>(); } 使用以下代码,我只得到第一级子产品: foreach (var items in lstcatlist) { CMBCat
public class CMBCategory
{
public int ID { get; set; }
public string Name { get; set; }
public List<CMBCategory> children = new List<CMBCategory>();
}
使用以下代码,我只得到第一级子产品:
foreach (var items in lstcatlist)
{
CMBCategory cmb = new CMBCategory();
cmb.ID = items.FirstOrDefault().catid;
cmb.Name = items.FirstOrDefault().title;
foreach (var item1 in items)
{
if (item1.parent == 0)
{
cmb.children.Add(new CMBCategory() { ID = item1.prod_id, Name = item1.desc });
}
}
lstmain.Add(cmb);
}
此处lstcatlist具有以下值:
这可能是因为我的循环结构,请提供一种方法,找到正确的结构,以循环n个子产品(如果有)
var lstcatlist = (from s in context.M_ProductCategory
join p in context.M_CategoryDetails on s.ID equals p.CategoryID
select new
{
catid = s.ID,
title = s.Title,
prod_id = p.ID,
parent = p.ParentID,
desc = p.Description
}).GroupBy(x => x.catid).ToList();
您需要使用递归
void main()
{
PrintTree(listOfCategorys);
}
void PrintTree(IEnumerable<CMBCategory> list)
{
foreach(var item in list)
{
PrintTree(item.children);
DoSomehtingWithTheObject(item); // ie. print it , or what ever you want
}
}
void main()
{
PrintTree(类别列表);
}
无效打印树(IEnumerable列表)
{
foreach(列表中的变量项)
{
打印树(项.子项);
是否与对象(项目)一起打印;//即,打印它,或您想要的任何内容
}
}
lstcatlist中的数据是什么?它的模型是什么?@Stephen Muecke List lstmain=new List();否-再次-什么在lstcatlist
中?它的型号是什么?@Stephen Muecke ohh抱歉!!!更新了有问题的值
void main()
{
PrintTree(listOfCategorys);
}
void PrintTree(IEnumerable<CMBCategory> list)
{
foreach(var item in list)
{
PrintTree(item.children);
DoSomehtingWithTheObject(item); // ie. print it , or what ever you want
}
}