简体   繁体   English

如何从匿名列表中选择父母及其所有孩子的列表

[英]How to pick List of parents and its all childs from anonymous list

My Linq2Sql statements gaves me what I what I required. 我的Linq2Sql语句给了我所需的信息。 Below is my method returning anonymous list of category and all its related subcategories: 下面是我的方法,返回类别及其所有相关子类别的匿名列表:

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
                               };
}

In my code behind i am using this method to fetch category and all its subcategory: 在后面的代码中,我正在使用此方法来获取类别及其所有子类别:

 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();
        }

Adding watch I got the stuff give below: 添加手表,我得到的东西如下:

[0] { p = {InnovativeTechnosoft.BusinessBazaar.Web.UI.Core.Category}, relatedchilds = {System.Collections.Generic.List`1[InnovativeTechnosoft.BusinessBazaar.Web.UI.Core.SubCategory]} }    <Anonymous Type>

Requirement : From code itself its clear that I need to iterate through the category and its subcategory. 要求:从代码本身可以清楚地看出,我需要遍历类别及其子类别。 I am trouble and condition check where I am using dt.OfType<Category>() . 我在使用dt.OfType<Category>()时遇到麻烦和状况检查。 If I use simply foreach(Category c in dt) , it gives me casting exception. 如果我只使用foreach(Category c in dt) ,它会给我强制转换异常。

Please help. 请帮忙。 Where and what I am doing wrong. 我在哪里和哪里做错了。

What your method GetAllCategoriesAndSubcategories() returns is an IQueryable of an anonymous type - instances of this type are not Category objects so the cast will always fail, and OfType<Category>() will simply return an empty collection. 您的方法GetAllCategoriesAndSubcategories()返回的是一个匿名类型的IQueryable此类型的实例不是Category对象,因此GetAllCategoriesAndSubcategories()类型转换将始终失败,并且OfType<Category>()将仅返回一个空集合。

Instead projecting to an anonymous type use a helper class that will allow you to use it later on, ie: 而是使用帮助程序类来投影为匿名类型,该类将允许您以后使用它,即:

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

Then change the method signature of GetAllCategoriesAndSubcategories to: 然后将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
                               };
}

Now you can query the returned enumeration like: 现在,您可以查询返回的枚举,例如:

foreach (CategoryWithSubcategories category in dt)
{
   //your code here
   foreach (var subCategory in category.RelatedSubCategories)
   {
     //more code here
   }
}

You're not returning Categories, you're returning an anonymous object that has a Category and an enumerable of Categories. 您没有返回类别,而是返回了一个具有类别和可枚举类别的匿名对象。

The easiest option, since you're not using the query in the same scope that you're creating it, is to make a simple object and to put the query results into that type, rather than using an anonymous type, that way you can cast to that. 最简单的选择,因为您不在创建查询的范围内使用查询,所以它是创建一个简单的对象并将查询结果放入该类型中,而不是使用匿名类型,因此您可以投给那个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM