[英]How to pick List of parents and its all childs from anonymous list
我的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)
,它会给我强制转换异常。
请帮忙。 我在哪里和哪里做错了。
您的方法GetAllCategoriesAndSubcategories()
返回的是一个匿名类型的IQueryable
此类型的实例不是Category对象,因此GetAllCategoriesAndSubcategories()
类型转换将始终失败,并且OfType<Category>()
将仅返回一个空集合。
而是使用帮助程序类来投影为匿名类型,该类将允许您以后使用它,即:
public class CategoryWithSubcategories
{
public Category SomeCategory {get;set;}
public IEnumerable<SubCategory> RelatedSubCategories {get;set;}
}
然后将GetAllCategoriesAndSubcategories
的方法签名GetAllCategoriesAndSubcategories
为:
public IQueryable<CategoryWithSubcategories> GetAllCategoriesAndSubcategories()
{
return from p in _context.Categories
let relatedchilds = from c in _context.SubCategories
where c.CategoryId == p.Id
select c
select new CategoryWithSubcategories
{
SomeCategory = p,
RelatedSubCategories = relatedchilds
};
}
现在,您可以查询返回的枚举,例如:
foreach (CategoryWithSubcategories category in dt)
{
//your code here
foreach (var subCategory in category.RelatedSubCategories)
{
//more code here
}
}
您没有返回类别,而是返回了一个具有类别和可枚举类别的匿名对象。
最简单的选择,因为您不在创建查询的范围内使用查询,所以它是创建一个简单的对象并将查询结果放入该类型中,而不是使用匿名类型,因此您可以投给那个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.