简体   繁体   English

Linq 带 OrderBy 字数的查询

[英]Linq query with OrderBy word count

I have this bit of code,我有这段代码,

 public static List<string> GetSentencesFromWords(List<string> words, string fileContents)
{
    return fileContents.Split('.')
        .Where(s => words.Any(w => s.IndexOf(w) != -1))
        .Select(s => s.TrimStart(' ') + ".")
        .ToList();
}

It works brilliantly, another user helped me with it in another question, but I thought my new question related to it warranted a new post.它工作得很好,另一个用户在另一个问题中帮助我解决了这个问题,但我认为与它相关的新问题需要一个新帖子。 I need the returned word list to be ordered by the number of matches in each sentence.我需要返回的单词列表按每个句子中的匹配数排序。 I have tried to do it a few ways but I am not very experienced with Linq and everything I have tried just seems to sort by sentence length rather than word count.我尝试过几种方法,但我对 Linq 不是很有经验,我尝试过的所有内容似乎都是按句子长度而不是字数排序。

Try this and it should work for you?试试这个,它应该适合你?

return fileContents.Split('.')
    .Where(s => words.Any(w => s.IndexOf(w) != -1))
    .Select(s => s.TrimStart(' ') + ".")
    .OrderByDescending(s => words.Count(w => s.IndexOf(w) != -1))
    .ToList();

What about this:那这个呢:

return fileContents.Split('.')
   .Where(s => words.Any(w => s.Contains(w) != -1))
   .Select(s => s.TrimStart(' ') + ".")
   .OrderByDescending(s => words.Sum(w => Regex.Matches(s, w).Count))
   .ToList();

don't forget to include using System.Text.RegularExpressions不要忘记using System.Text.RegularExpressions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM