简体   繁体   中英

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.

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM