As an example of what I’m trying to accomplish, here is some code which builds out a list of books with a string property called Sentence.
public class Book {
public string Sentence { get; set; }
}
Book book1 = new Book() { Sentence = "The quick brown fox jumps over the lazy dog" };
Book book2 = new Book() { Sentence = "The quick brown frog jumps over the lazy sloth" };
List<Book> books = new List<Book>();
books.Add(book1);
books.Add(book2);
I want to search through the list of books based on some user input (the search requirements shouldn’t get more complicated than this example).
If a user provides a search phrase of quick fox "lazy dog", then I went to return a List which has book1 as a member of the collection. If a user provides a search phrase of quick fox sloth nothing should be returned because those three words do not all appear in any of the properties.
Summary
-
quick fox "lazy dog"– 1 Result (the words in quotes appear together, and the remaining words appear individually) -
quick fox sloth– No results -
"lazy sloth"– 1 Result (both words appear together in the string) -
lazy sloth– 1 Result (both words appear individuals in the string)
The code that I currently have:
//Turn the search word into an array of words (includes support for quotes phrases). E.g: quick fox "lazy dog" becomes a list of these values: `quick`, `fox`, `lazy dog`.
var searchWords = Regex.Matches(searchWord, @"(?<match>\w+)|\""(?<match>[\w\s]*)""")
.Cast<Match>()
.Select(m => m.Groups["match"].Value)
.ToList();
var query = from b in books
where (!string.IsNullOrEmpty(b.Sentence) && searchWords.Any(b.Sentence.Contains))
select b;
This doesn’t work for case 2. The code I have now is just looking for 1 match, and if it gets 1 match then it considers the item found.
I think you might want the
All()LINQ method, try this: