您可以創建方法,建立從給出的單詞短語。效率不是很高(因爲跳過),但簡單的實現:
private static IEnumerable<string> CreatePhrases(string[] words, int wordsCount)
{
for(int i = 0; i <= words.Length - wordsCount; i++)
yield return String.Join(" ", words.Skip(i).Take(wordsCount));
}
休息很簡單 - 分割你的串入的話,建立短語,並獲得原始字符串每個短語的出現:
var my_string = "In the end this is not the end";
var words = my_string.Split();
var result = from p in CreatePhrases(words, 2)
group p by p into g
select new { g.Key, Count = g.Count()};
結果:
[
Key: "In the", Count: 1,
Key: "the end", Count: 2,
Key: "end this", Count: 1,
Key: "this is", Count: 1,
Key: "is not", Count: 1,
Key: "not the", Count: 1
]
創建項目的連續組(更有效的方法適用於任何我枚舉):
public static IEnumerable<IEnumerable<T>> ToConsecutiveGroups<T>(
this IEnumerable<T> source, int size)
{
// You can check arguments here
Queue<T> bucket = new Queue<T>();
foreach(var item in source)
{
bucket.Enqueue(item);
if (bucket.Count == size)
{
yield return bucket.ToArray();
bucket.Dequeue();
}
}
}
而且所有的計算可以在一個行完成:
var my_string = "In the end this is not the end";
var result = my_string.Split()
.ToConsecutiveGroups(2)
.Select(words => String.Join(" ", words))
.GroupBy(p => p)
.Select(g => new { g.Key, Count = g.Count()});
謝謝,我錯過了。 – tribe84 2014-10-28 20:38:51
@GrantWinney - 不,這兩個問題是相似的,但不一樣。 – tribe84 2014-10-28 20:39:39
你想如何分割'input'? – 2014-10-28 20:49:59