Greg B
Greg B

Reputation: 813

LINQ: search 2 properties for a list of strings

I have a the following in varies parts of my code:

QuestionModel:

public class QuestionModel {
    public string Question { get; set; }
    public string Answer { get; set; }
}

Keywords:

List<string> SearchKeywords

Questions:

List<QuestionModel> Questions

What I would like to achieve is from a list of ALL questions, to search and retain all questions that have ALL the keywords.

I'm gone as far as this but hit a road block:

var questions = GetAllQuestions(); //returns all questions as a List<QuestionModel>
Questions = questions.All(x => SearchKeywords.All(k => x.Question.Contains(k) || x.Answer.Contains(k)));

This however returns a bool.

Any help or directions would be appreciated.

Upvotes: 0

Views: 97

Answers (2)

It&#39;sNotALie.
It&#39;sNotALie.

Reputation: 22794

The first All is wrong. You need Where:

Questions = questions.Where(x => SearchKeywords.All(k => x.Question.Contains(k) || x.Answer.Contains(k))).ToList();

Also, as Questions is a List<QuestionModel>, you need ToList.

Upvotes: 1

Jon
Jon

Reputation: 437336

You are using the wrong LINQ method, you want Where instead of All:

Questions = questions.Where(x => ...);

All tells you if every item in the collection satisfies a condition (boolean result); Where filters the elements that satisfy the condition (filtered collection result).

Depending on what Questions is exactly (looks like a property, of what type?) you may have to wrap it up with ToList or ToArray.

Upvotes: 5

Related Questions