【发布时间】:2012-02-01 04:13:54
【问题描述】:
我的 Linq2Sql 语句给了我我所需要的。以下是我返回类别及其所有相关子类别的匿名列表的方法:
public IQueryable GetAllCategoriesAndSubcategories()
{
return from p in _context.Categories
let relatedchilds = from c in _context.SubCategories
where c.CategoryId == p.Id
select c
select new
{
p,
relatedchilds
};
}
在我后面的代码中,我使用此方法来获取类别及其所有子类别:
private void WriteCategories()
{
var repository = new CategoryRepository();
var dt = repository.GetAllCategoriesAndSubcategories();
var sb = new StringBuilder();
sb.AppendLine(" <div class='widget_box' id='category'>");
sb.AppendLine(" <div class='wintitle'>");
sb.AppendLine(" <div class='inner_wintitle'>Categories</div>");
sb.AppendLine(" </div>");
sb.AppendLine(" <div class='winbody'>");
sb.AppendLine(" <ul class='categories'>");
int i = 1;
foreach (Category category in dt.OfType<Category>())
{
sb.AppendLine(
string.Format("<li class='catetitle' id='catetitle{0}'><a href='/category/{1}/{2}'>{3}</a></li>", i,
category.Id, Common.ReplaceUnwantedChars(category.Name), category.Name));
sb.AppendLine("<li style='display:none;' class='category_sub' ><div><ul>");
foreach (var subCategory in dt.OfType<SubCategory>())
{
sb.AppendLine(string.Format("<li><a href='category/{0}/{1}/{2}'>{3}</a></li>", category.Id,
subCategory.Id, Common.ReplaceUnwantedChars(subCategory.Name),
subCategory.Name));
}
i++;
}
sb.AppendLine("</div></ul></div>");
ltlCategories.Text = sb.ToString();
}
添加手表我得到了以下内容:
[0] { p = {InnovativeTechnosoft.BusinessBazaar.Web.UI.Core.Category}, relatedchilds = {System.Collections.Generic.List`1[InnovativeTechnosoft.BusinessBazaar.Web.UI.Core.SubCategory]} } <Anonymous Type>
要求:从代码本身来看,我需要遍历类别及其子类别。我在使用dt.OfType<Category>() 时遇到麻烦和状况检查。如果我只使用foreach(Category c in dt),它会给我投射异常。
请帮忙。我在哪里做错了什么。
【问题讨论】:
标签: c# asp.net linq-to-sql