【问题标题】:How to pick List of parents and its all childs from anonymous list如何从匿名列表中选择父母及其所有孩子的名单
【发布时间】: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&lt;Category&gt;() 时遇到麻烦和状况检查。如果我只使用foreach(Category c in dt),它会给我投射异常。

请帮忙。我在哪里做错了什么。

【问题讨论】:

    标签: c# asp.net linq-to-sql


    【解决方案1】:

    您的方法 GetAllCategoriesAndSubcategories() 返回的是匿名类型的 IQueryable - 此类型的实例不是 Category 对象,因此强制转换总是会失败,OfType&lt;Category&gt;() 只会返回一个空集合。

    使用一个帮助类来代替投影到匿名类型,以便您以后使用它,即:

    public class CategoryWithSubcategories
    {
       public Category SomeCategory {get;set;}
       public IEnumerable<SubCategory> RelatedSubCategories {get;set;}
    }
    

    然后将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
       }
    }
    

    【讨论】:

    • @AmitRanjan:调试器允许您查看匿名类型的属性,但接收方法不知道该类型本身,因为您只返回一个 IQueryable - 您必须返回一个强类型对象,请参阅更新的答案。
    • “使用帮助类来代替投影到匿名类型,这样您以后可以使用它。” - 请多解释一下你想说什么...
    【解决方案2】:

    您返回的不是类别,而是一个匿名对象,该对象具有类别和类别的可枚举。

    最简单的选择是创建一个简单的对象并将查询结果放入该类型,而不是使用匿名类型,因为您没有在创建它的同一范围内使用查询你可以投射到那个地方。

    【讨论】:

    • 实际上我的数据库上有两个表 Category 和 Subcategory。所以我想在一个列表中返回所有类别及其子类别。所以我就这么做了。我不能只返回类别。任何想法都一样..
    • 正如 BrokenGlass 更详细地解释的那样,您需要创建一个新类来保存您想要的数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多