Tanuki
Tanuki

Reputation: 363

How to execute a linq query for each item in a list , use it in the where clause and return a collection from the result of each query?

As you can see I'm executing the query for the first element in the list. I would like to execute the query for each category in the list and to return one collection with the result of all queries without duplicates (A question can be in multiple categories).

public ObservableCollection<Question> GetQuestionsByCategory(List<Category> categories) 
{
    var c = categories[0];
    var questions = from q in this.Questions where q.Categories.Contains(c)
                    select q;

    return new ObservableCollection<Question>(questions);
}

Upvotes: 0

Views: 146

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156459

You could do this:

var questions = 
    (from c in categories
    from q in this.Questions where q.Categories.Contains(c)
    select q).Distinct();

But I'd suggest this instead:

var questions = from q in this.Questions
                where q.Categories.Any(c => categories.Contains(c))
                select q;

Upvotes: 1

Related Questions