成对迭代在C#或滑动窗口枚举窗口、迭代

2023-09-02 11:47:04 作者:浪子未归

如果我有一个IEnumerable这样的:

If I have an IEnumerable like:

string[] items = new string[] { "a", "b", "c", "d" };

我想环通连续的项目(滑动大小为2的窗口)中的所有对。这将是

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")

我的解决方案是为这个

My solution was is this

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

在我写这篇code,我想知道是否有已经在.NET框架,做同样的事情功能,做到这一点不只是对,但为任何规模大小元组。 恕我直言应该有一个很好的方式做这样的滑动窗口的操作。

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)有更多的(并且更好)的方式来做到这一点,但我主要是在C#2.0的解决方案感兴趣。虽然,我也将AP preciate 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));