本文介绍了使用LINQ/.NET MVC对搜索结果排名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项任务,需要根据找到搜索词的列对搜索结果进行排名.

I have a task where I need to rank the search results based on which column the search term was found.

因此,例如,如果在表1的A列中找到搜索词,则其排名要比在表2的A列中找到的搜索词排名更高.

So for example, if the search term is found in column A of table 1, it ranks higher than if it was found in column A of table 2.

现在,我有一个linq查询,该查询连接多个表并在某些列中搜索搜索词. I.E.

Right now, I have a linq query that joins multiple tables and searches for the search term in certain columns. I.E.

var results = db.People
    .Join(db.Menu, p => p.ID, m => m.PersonID, (p, m) => new { p = p, m = m })
    .Join(db.Domain, m => m.m.DomainID, d => d.ID, (m, d) => new { m = m, d = d })
    .Where(d => searchTermArray.Any(x => d.m.p.p.Name.Contains(x)) || searchTermArray.Any(x => d.m.p.p.Biography.Contains(x)) || searchTermArray.Any(x => d.d.domain.Contains(x)))
    .Select(p => p).Distinct();

因此,如果在db.People的列Name中找到搜索项,则该行/人的排名将比在db.People的列Biography中所找到的排名高,而在db.People的列Biography中将找到更高的排名.

So if the search term is found in db.People, column Name, that row/Person will rank higher than if found in db.People, column Biography, which will rank higher than if found in db.Domain, column domain.

推荐答案

这将按排名"对您的结果进行排序.如果您还想返回排名而不是返回汇总,则可以进一步处理查询:

This will order your result by the "rank". You can manipulate the query further if you also want to return the rank and not only the aggregate:

var results = db.People
    .Join(db.Menu, p => p.ID, m => m.PersonID, (p, m) => new { p = p, m = m })
    .Join(db.Domain, m => m.m.DomainID, d => d.ID, (m, d) => new { m = m, d = d })
    .Select(d => new
            {
                rank = searchTermArray.Any(x => d.m.p.p.Name.Contains(x)) ? 3 : searchTermArray.Any(x => d.m.p.p.Biography.Contains(x)) ? 2 : searchTermArray.Any(x => d.d.domain.Contains(x)) ? 1 : 0,
                m = d
            })
    .Where(a => a.rank > 0)
    .OrderByDescending(a => a.rank)
    .Select(a => a.m).Distinct();

注意:我对性能不佳不承担任何责任,毕竟这就是LINQ.

Note: I take no responsibility for poor performance, that's LINQ after all.

这篇关于使用LINQ/.NET MVC对搜索结果排名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 00:51