I have this code which, on the front-end, will create dependent selectboxes (subcategories are dependent on the category) using LINQ:
foreach (var cat in (from category in KB.Categories
orderby category.name
select category)) {
this.categories.Add(cat.id, cat.name);
}
foreach (var sub_cat in (from subcategory in KB.SubCategories
orderby subcategory.name
select subcategory)) {
this.subcategories.Add(sub_cat.id, sub_cat.name);
if (!this.subcategoryCategory.containsKey) {
this.subcategoryCategory.Add(sub_cat.category_id, new ArrayList());
}
// I'd like to put the sub_cat_id at the end of the arraylist
// for the category_id, but this line doesn't seem to work
//this.subcategoryCategory[sub_cat.category_id] = sub_cat.id;
}
How can I do this?
Perhaps there a way to build a giant JSON object instead of the three variables (c开发者_StackOverflow中文版ategories, subCategoryCategory, subcategories)?
Is there a better/different way to do this that I've completely missed?
P.S. Coming from a different programming paradigm, I'm not doing this in the standard ASP.NET (webforms or MVC) way, but I am using codebehind to generate the values.
It looks like you actually want a Lookup, e.g.
var subcategories = KB.SubCategories.ToLookup(subcat => subcat.id,
subcat => subcat.name);
However, it's not really clear given that you've got subcategories, subcategoryCategory and categoies, all of which are instance variables which you haven't shown us the type for... and your if clause doesn't specify which key it's trying to use. It's all a bit confused at the moment...
My guess is that you should look at ToLookup and also ToDictionary, which are made for this sort of thing.
JSON.NET might solve this problem, with its ability to convert JSON objects to C# and back. See this SO question for an example.
加载中,请稍侯......
精彩评论