2014-02-13 50 views
5

有没有一种方法可以通过从字符串数组中匹配的字数来排序字符串列表?如何排序与Linq中的数组匹配的字数字符串列表

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); 
} 

有没有一种方法来生成输出,而无需使用其他listfor循环排序

one two three little pony 
one two little pony 
one little pony 
little pony 

回答

7

使用Count而不是Any

x = x.OrderByDescending(u => targets.Count(u.Contains)).ToList(); 
+0

谢谢斯坦利。我在原来提交的代码中犯了一个错误。我编辑了代码。请编辑你的答案从'u.Tags.Contains'到'u.Contains',以使其与编辑的代码更相关。 –

+0

@FloodGravemind完成。 –

3

这种种的另一种方法原始列表List.Sort i创建一个新的nstead:

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 *用于降序排序,所以最出现在上面。由于您提到您要计数,因此这也会被搜索子字符串的空白插入分割。

我已经使用了HashSet<string>,因为查找效率更高,而且重复不应该只计算一次以上。

1
var query = list.OrderByDescending(phrase => 
    phrase.Split().Intersect(targets).Count()); 

你在这里概念上做的是看两组词汇的交集。交集是两个其他集合中存在的集合。