LINQ可以用来从字符串中提取关键字吗?

时间:2013-04-18 03:44:31

标签: c# string linq

如果我有一个长文本字符串并且想要提取长度大于4个字符且在字符串中发现超过4次的单词,LINQ可以这样做吗?

1 个答案:

答案 0 :(得分:15)

你可能会收紧这个,但我相信它会产生一些影响

var results = inputstring.Split()
                .Where(word => word.Length > 4)
                .GroupBy(word => word)
                .Where(grp => grp.Count() > 4)
                .Select(grp => grp.Key);

当然,您需要决定如何处理可能存在的标点符号。

所以给出了输入

var inputstring = @"The quick brown fox jumped over the lazy dog 
               The quick brown fox jumped over the lazy dog 
               The quick fox jumped over the lazy dog 
               The quick fox jumped over the lazy dog 
               The quick brown fox jumped over the lazy dog";

结果包含“快速”和“跳跃”,因为大于4个字符(“褐色”)的唯一其他单词只出现了3次。