C# Linq按匹配数排序

C# Linq按匹配数排序,c#,asp.net,linq,linq-to-sql,search,C#,Asp.net,Linq,Linq To Sql,Search,我有一个字符串数组和一个Linq查询: /// <summary> /// Return all the search results /// </summary> public static GenericTagEntity[] getSearchResults(int SectionID, string[] Words) { GenericTagEntity[] Recs; using (MainContext db = new MainContex

我有一个字符串数组和一个Linq查询:

/// <summary>
/// Return all the search results
/// </summary>
public static GenericTagEntity[] getSearchResults(int SectionID, string[] Words)
{
    GenericTagEntity[] Recs;

    using (MainContext db = new MainContext())
    {
        var q = (
            from c in db.tblArticles
            join a in db.tblForumAuthors on c.AuthorID equals a.Author_ID
            join u in db.tblProfiles on c.AuthorID equals u.UserID
            where c.IsDeleted == false
            && c.SectionID == SectionID
            select new
            {
                c.Title,
                c.ID,
                c.Anchor,
                c.Date,
                c.Description,
                u.EmailAddress,
                u.UserID,
                a.Username,
                c.Body,
                comments = (from f in db.tblComments where f.IsDeleted == false && f.Anchor == c.Anchor select new { f.ID }).Count()
            });
我想做的是修改where,以便它返回c.Title或c.Body包含一个或多个单词的结果。然后我需要它的总匹配最相关的第一

这对我来说真的很难,非常感谢您的帮助

我发现了这一点,但它只是部分有用,而且搜索结果也不多。

很抱歉打断您,但您使用了错误的工具来解决此问题。在db中创建全文索引并通过自定义函数从LINQ调用全文搜索,或者使用第三方全文搜索系统行Lucene

如果您真的想在sql中这样做,那么计算文档中单词的实例数将需要您更改db模式


您需要一个words表id、word和一个occurrences表wordid、articleid,然后您可以在occurrences表上进行查询以获得所需的结果。

我相信这会达到目的

var occurrences = from e in q.Title.Split(new char[] { ' ' }).Concat(q.Body.Split(new char[] { ' ' }))
             join word in Words on e equals word
             group e by e into g
             select new {element = g, count = g.Count()} into result
             orderby result.count descending
             select result;

该查询将生成一个按出现次数降序排列的标题或正文中的单词列表。

您使用的是哪种LINQ提供程序?LINQ to SQL?是的,只搜索两列并不是太难或太慢,但是计算字数-如果您想编写原始SQL,您可以这样做,尽管性能比您的建议差得多,但我想不出任何方法在LINQ to SQL中实现这一点。也就是说,不使用.ToEnumerable,最终都希望有合理的性能。orderby count做得很好