有没有办法在 LINQ 中编写查询以返回在字段中找到的搜索词的计数
基本上,我希望它能工作:
var matches = from t in _db.Books
let score = GetScore(t, searchterms)
where score >= 1
orderby score descending
select t;
public static int GetScore(Book b, params string[] searchterms)
{
int count = 0;
foreach (string term in searchterms)
{
if (b.Title.Contains(term))
count++;
}
return count;
}
但是,当然,这是行不通的。 我的小 GetScore 函数可以转换为 LINQ 吗?
谢谢。
编辑:我也希望乐谱可以访问。理想情况下,我会将我的结果选择到一个 SearchResults 类(对于 View )中,该类将包含一些图书信息和来自查询的图书分数。要更新我的查询,它会是这样的:
var matches = from t in _db.Books
let score = GetScore(t, searchterms)
where score >= 1
orderby score descending
select new SearchResult
{
Title = t.Title,
Type = "Book",
Link = "Books/Details/" + t.BookID,
Score = score
};
对不起,我最初没有更清楚。
最佳答案
如果不向数据库发出多个查询(基本上是每个搜索词一个),您就无法做您想做的事。如果您乐于这样做,那么这里有一个简单的方法:
var terms = new [] { "s", "t", "r", "e", "b", "c", };
var ids =
from term in terms
from id in _db.Books
.Where(book => book.Title.Contains(term))
.Select(book => book.Id)
group term by id into gts
orderby gts.Count() descending
select gts.Key;
var selectedIds = ids.Take(50).ToArray();
var query =
from book in _db.Books
where selectedIds.Contains(book.Id)
select book;
我编写了 ids
以返回一个 id 列表,这些 id 按最先匹配的项排序。这是为了最接近地获得您在问题中想要的相同类型的结果。然后我决定使用 Take(50)
来获得前 50 个结果。您显然可以更改此策略以满足您的需要,但您必须以一组 ID 结束以在最终查询中使用。
希望对您有所帮助。
编辑:基于 OP 的编辑。
下面是查询包含分数的方法:
var terms = new [] { "s", "t", "r", "e", "b", "c", "l", "i", };
var idScores =
from term in terms
from id in _db.Books
.Where(book => book.Title.Contains(term))
.Select(book => book.BookID)
group term by id into gts
select new
{
Id = gts.Key,
Score = gts.Count(),
};
var selectedIds = idScores.Select(x => x.Id).Take(50).ToArray();
var selectedBooks =
from book in _db.Books
where selectedIds.Contains(book.BookID)
select book;
var query =
from b in selectedBooks.ToArray()
join x in idScores on b.BookID equals x.Id
orderby x.Score descending
select new
{
Title = b.Title,
Type = "Book",
Link = "Books/Details/" + b.BookID,
Score = x.Score,
};
关于c# - LINQ to SQL,我如何获得在字段中找到的搜索词的计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4332083/