【问题标题】:How to add values to a list in mvc 4?如何将值添加到 mvc 4 中的列表?
【发布时间】:2016-09-01 05:24:49
【问题描述】:

我的模型定义为:

public class CMBCategory
{
    public int ID { get; set; }
    public string Name { get; set; }
    public List<CMBCategory> children = new List<CMBCategory>();
}

我需要向这个列表中添加值,但可能有 n 个子项,例如

a)Redbook
    a.1) Wedding
          a.1.1) Christian
              .
              .
    a.2)Baptism
b)Florenta

使用以下代码,我只得到第一级子产品:

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();

【问题讨论】:

  • lstcatlist中的数据是什么,它的模型是什么?
  • @Stephen Muecke List lstmain = new List();
  • 不 - 再次 - lstcatlist 中有什么,它的模型是什么?
  • @Stephen Muecke 哦,对不起!!!
  • 更新了有问题的值

标签: c# asp.net-mvc-4 for-loop


【解决方案1】:

你需要使用递归

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 

  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多