score:8

Accepted answer

You don't need to write two Where clauses; just add another condition to your first Where. The second condition should use Any function to search for the categories you're looking for.

IArticleRepository articleRepo = unitOfWork.ArticleRepository;
List<Article> articles = new List<Article>(
                     articleRepo.GetAll()
                     .Where(a => a.Title == searchTerm &&
                                 a.Categories.Any(c => c.CategoryID == 4))
                     .OrderByDescending(a => a.CreatedDate));  

For multiple categories, suppose you have your CategoryIDs in an int[] or List<int> named MyCatIDsList. They you can change the categories clause in the above query to this:

              a.Categories.Any(c => MyCatIDsList.Contains(c.CategoryID))

score:2

You don't need to create a new list and you can use several where expressions in one Where clause. Can you try the following code:

List<Article> articles = articleRepo.GetAll()
                     .Where(a => a.Title == searchTerm && a.Categories.Contains(Category)).OrderByDescending(a => a.CreatedDate)).ToList();  

score:3

There is an alternative syntax when using LINQ queries, which is more like SQL. The code above is correct, but you may find this version more concise:

int categoryId = 4
IArticleRepository articleRepo = unitOfWork.ArticleRepository;
var articlesQuery = from article in articleRepo.GetAll()
                    from category in article.Categories

                    where category.CategoryId == categoryId
                    where article.Title == searchTerm
                    orderby article.CreatedDate descending

                    select article

List<Article> articles = articlesQuery.ToList();

Or its more common to do these all together in one step:

int categoryId = 4
List<Article> articles =   (   
                             from article in articleRepo.GetAll()
                             from category in article.Categories

                             where category.CategoryId == categoryId
                             where article.Title == searchTerm
                             orderby article.CreatedDate descending

                             select article
                           ).ToList()

Related Articles