Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 385
SpectralEdge Avatar asked Feb 21 '23 22:02

SpectralEdge


1 Answers

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();
like image 118
mattytommo Avatar answered Feb 27 '23 22:02

mattytommo