Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you sort a String List by the number of words matched with an Array in Linq

Tags:

c#

linq

Is there a way to sort a String List by the number of words matched from a string array?

var targets = new string[] { "one", "two", "three" };
var list = new List<string>();
    list.Add("one little pony");
    list.Add("one two little pony");
    list.Add("one two three little pony");
    list.Add("little pony");
x = x.OrderByDescending(u => targets.Any(u.Contains)).ToList();
foreach(var item in list)
{
 Debug.Writeline(item);
}

Is there a way to generate an output without using another list or for loop to sort

one two three little pony
one two little pony
one little pony
little pony
like image 390
Flood Gravemind Avatar asked Feb 13 '14 15:02

Flood Gravemind


2 Answers

Use Count instead of Any:

x = x.OrderByDescending(u => targets.Count(u.Contains)).ToList();
like image 185
D Stanley Avatar answered Oct 23 '22 10:10

D Stanley


Another approach which sorts the original list with List.Sort instead of creating a new one:

var targets = new HashSet<string> { "one", "two", "three" };
list.Sort((s1, s2) => -1 * (s1.Split().Count(targets.Contains)
                 .CompareTo(s2.Split().Count(targets.Contains))));

-1 * is used to sort descending, so the most occurrences on top. This also splits by white-space insetad of searching sub-strings since you've mentioned that you want to count words.

I've used a HashSet<string> since it's more efficient for lookups and duplicates should not be counted more than once anyway.

like image 44
Tim Schmelter Avatar answered Oct 23 '22 11:10

Tim Schmelter