换句话说,我需要列表“ Categories ”的所有元素都是“Parent”,列表“商品”的元素是孩子。
实施例
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;
}
在这个foreach中,看看每个类别中的所有商品名称是否可能。
我尝试添加动态列表,例如:
dynamic listOfElements = new { CAT = categories, COMM = commodities };
但它不会将元素作为父母或类别的依赖关系返回。与添加
相同commodities.Add(new
{
comcat.Category,
com.Name,
});
答案 0 :(得分:0)
您的班级结构不支持父子关系。我的意思是,如果你想要的是每个类别都有一个商品清单,那么你需要这样的东西:
var result = from c in comcat
select new { Category = c, Commoddities = c.Commoddities};
这将返回类别的层次结构,包括其下的所有商品。
如果您刚收到平面数据集,那么您需要这样的内容:
var result = from c in comcat
select new { Category = c,
Commoddities = c.Where(x=>x.Category.Name == c.Name).Select(x=>x.Commodity) };
希望你明白了......
答案 1 :(得分:0)
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);
}