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
Use Count
instead of Any
:
x = x.OrderByDescending(u => targets.Count(u.Contains)).ToList();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With