简体   繁体   中英

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

My Linq2Sql statements gaves me what I what I required. 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>() . If I use simply foreach(Category c in dt) , it gives me casting exception.

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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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