Arif YILMAZ Arif YILMAZ - 13 days ago 5
C# Question

How to create complex Custom object from LINq

I am trying to create a list of custom objects in LINQ, and I am not sure how to do it. Here is my classes...

public class MenuModel
{
public IList<MenuCategoriesWithArticles> Menu { get; set; }
}

public class MenuCategoriesWithArticles
{
public Category Category { get; set; }
public IList<Article> Articles { get; set; }
}


and I would like to create MenuModel from the following functions that return Category and IList in order.

businessCategory.GetAllCategories();
businessArticle.GetArticlesByCategory(int categoryId);


I have something like below but I am not sure...

businessCategory.GetAllCategories().Select(x=> new .....)


any help would be great. I dont want to loop to get each categories' articles.

Answer

Maybe something like this could help you.

businessCategory.GetAllCategories().Select(x=> new MenuCategoriesWithArticles{
   Category = x,
   Articles = businessArticle.GetArticlesByCategory(x.categoryId).ToList();
});

The only thing is, if GetArticlesByCategory does a database search this code won't be optimal; if that is the case, you should query all the articles separately depending on the categories you select first.

Comments