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 Query

More Query from same tag