問題描述
如果我有一個(gè)像這樣的 IEnumerable:
If I have an IEnumerable like:
string[] items = new string[] { "a", "b", "c", "d" };
我想循環(huán)遍歷所有成對(duì)的連續(xù)項(xiàng)目(大小為 2 的滑動(dòng)窗口).會(huì)是
I would like to loop thru all the pairs of consecutive items (sliding window of size 2). Which would be
("a","b"), ("b", "c"), ("c", "d")
我的解決方案是這樣的
public static IEnumerable<Pair<T, T>> Pairs(IEnumerable<T> enumerable) {
IEnumerator<T> e = enumerable.GetEnumerator(); e.MoveNext();
T current = e.Current;
while ( e.MoveNext() ) {
T next = e.Current;
yield return new Pair<T, T>(current, next);
current = next;
}
}
// used like this :
foreach (Pair<String,String> pair in IterTools<String>.Pairs(items)) {
System.Out.PrintLine("{0}, {1}", pair.First, pair.Second)
}
當(dāng)我編寫這段代碼時(shí),我想知道 .NET 框架中是否已經(jīng)有函數(shù)可以做同樣的事情,而且不僅適用于對(duì),而且適用于任何大小的元組.恕我直言,應(yīng)該有一種很好的方法來(lái)執(zhí)行這種滑動(dòng)窗口操作.
When I wrote this code, I wondered if there are already functions in the .NET framework that do the same thing and do it not just for pairs but for any size tuples. IMHO there should be a nice way to do this kind of sliding window operations.
我使用 C# 2.0,我可以想象使用 C# 3.0(w/LINQ)有更多(更好)的方法可以做到這一點(diǎn),但我主要對(duì) C# 2.0 解決方案感興趣.不過,我也會(huì)欣賞 C# 3.0 解決方案.
I use C# 2.0 and I can imagine that with C# 3.0 (w/ LINQ) there are more (and nicer) ways to do this, but I'm primarily interested in C# 2.0 solutions. Though, I will also appreciate C# 3.0 solutions.
推薦答案
在 .NET 4 中這變得更加容易:-
In .NET 4 this becomes even easier:-
var input = new[] { "a", "b", "c", "d", "e", "f" };
var result = input.Zip(input.Skip(1), (a, b) => Tuple.Create(a, b));
這篇關(guān)于C# 或滑動(dòng)窗口枚舉器中的成對(duì)迭代的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!