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

编程入门 行业动态 更新时间:2024-10-22 07:31:45
本文介绍了成对迭代在C#或滑动窗口枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我有一个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));

更多推荐

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

本文发布于:2023-11-28 20:58:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643927.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:窗口   迭代

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!