Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

c# - Ranking Search Results With LINQ/.NET MVC

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

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.

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();

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...