1

I want to implement a Page where each Category have its related articles, I have implemented it as follow:

  ArticlesHomeViewModel articles  = new ArticlesHomeViewModel
  { 
    category1 = db.Articles.Include(o => o.Category).Where(m => m.category == "Category One Name").limit(4),
    category2 = db.Articles.Include(o => o.Category).Where(m => m.category == "Category two Name").limit(4),
    category3 = db.Articles.Include(o => o.Category).Where(m => m.category == "Category Three Name").limit(4),
    category4 = db.Articles.Include(o => o.Category).Where(m => m.category == "Category Four Name").limit(4),
  }

And I want to merge them into one query to be able to loop against them in the view because I don't know how many categories that could be in the system.

L_J
  • 2,351
  • 10
  • 23
  • 28
shady
  • 17
  • 5

1 Answers1

0

Define a category array.

var categories = new[]{"Category One Name","Category Two Name",
                       "Category Three Name","Category Four Name"};

Then

// Include is redundant
var result = db.Articles.Where(art=> categories.Contains(art.Category.Name)) 
            .GroupBy(art=>art.CateGory.Name) // use group for feature uses
            .SelectMany(grouped=>// use selectmany to select individual items
                grouped.OrderBy(t=>t.Id).Take(4))  // and apply paging in group
            .ToArray();  

Eldar
  • 9,781
  • 2
  • 10
  • 35