简体   繁体   English

如何在c#中使用foreach在列表内创建列表?

[英]How can I create a list inside a list with a foreach in c# ?

In other words I need all the elements of list " Categories " to be the "Parent" and elements of list " commodities " be the children. 换句话说,我需要将“ 类别 ”列表中的所有元素作为“父项”,而将“ 商品 ”列表中的所有元素作为子项。

Example

public string GetCommodities()
    {
        List<dynamic> categories = new List<dynamic>();
        List<dynamic> commodities = new List<dynamic>();

        foreach (var comcat in QuickQuoteRepo.CommodityCategories.All().OrderBy(o => o.Order))
        {
            categories.Add(new
            {
                comcat.Category,
            });
            foreach (var com in comcat.Commodities.OrderBy(o => o.Name))
            {
                commodities.Add(new
                {
                    com.Name,
                });
            }
        }
        var response = new JavaScriptSerializer().Serialize(commodities);

        return response;
    }

And see if it's possible to all commodities names inside each category, within this foreach. 并查看是否有可能在此foreach中每个类别内的所有商品名称。

I tried adding a dynamic list such as: 我尝试添加动态列表,例如:

dynamic listOfElements = new { CAT = categories, COMM = commodities };

But it does't return elemnts as parents or dependency of categories. 但是,它不会将elemnts作为父级或类别的依赖关系返回。 Is the same as adding 与添加相同

commodities.Add(new
                {
                   comcat.Category,
                    com.Name,
                });

You class structure does not support parent-child relationships. 您的班级结构不支持父子关系。 I mean, if what you want is that each Category holds a list of commodities, then you would need something like this: 我的意思是,如果您想要的是每个类别都包含商品列表,那么您将需要以下内容:

var result = from c in comcat 

             select new { Category = c, Commoddities = c.Commoddities};        

This will return a hierarchy of Categories including all Commodities underneath it. 这将返回类别的层次结构,包括其下的所有商品。

If you are just receiving a flat data set, then you need something like this: 如果您只是收到一个平面数据集,则需要这样的东西:

var result = from c in comcat 
             select new { Category = c, 
                          Commoddities = c.Where(x=>x.Category.Name == c.Name).Select(x=>x.Commodity) };        

Hopefully you get the idea... 希望你有主意...

public string GetCommodities()
{
    List<dynamic> categoryCommodityList = new List<dynamic>();
    foreach (var comcat in QuickQuoteRepo.CommodityCategories.All().OrderBy(o => o.Order))
    {
        var allCommodities = comcat.Commodities.OrderBy(o => o.Name).Select(com => com.Name).ToList();
        categoryCommodityList.Add(new { Catagory = comcat.Category, Items = allCommodities } );
    }
    return new JavaScriptSerializer().Serialize(categoryCommodityList);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM