作为我想要完成的一个例子,这里有一些代码可以构建一个带有名为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);
我想根据一些用户输入搜索书籍列表(搜索要求不应该比这个例子更复杂。)
如果用户提供的搜索短语为quick fox "lazy dog"
,那么我将返回一个List1,其中book1作为该集合的成员。如果用户提供quick fox sloth
的搜索短语,则不应返回任何内容,因为这三个单词并非全部出现在任何属性中。
摘要
quick fox "lazy dog"
- 1结果(引号中的单词一起显示,其余单词单独显示)
quick fox sloth
- 没有结果
"lazy sloth"
- 1个结果(两个单词一起显示在字符串中)
lazy sloth
- 1个结果(两个单词都出现在字符串中)
我目前拥有的代码:
//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;
这对案例2不起作用。我现在的代码只是寻找1个匹配,如果它得到1个匹配,那么它会考虑找到的项目。
答案 0 :(得分:1)
我想你可能想要All()
LINQ方法,试试这个:
var query = from b in books
where (!string.IsNullOrEmpty(b.Sentence) && searchWords.All(word => b.Sentence.Contains(word)))
select b;
答案 1 :(得分:1)
我会使用Lucene.Net而不是重新发明轮子。您甚至不需要磁盘上的索引。所有索引+搜索都可以在内存中完成(使用Lucene的RamDirectory)