0

让我们考虑一个IEnumerable算法,该算法采用成对的重叠索引,例如 {0, 1}, {1, 2}, {2, 3} 等。 end 根据这些索引的值创建一个新集合,例如 {collection[0] , collection[1] => result[0]}, {collection[1], collection[2] => result[1]} 等等。下面是一个直接实现的例子:

IEnumerable<string> collection = new string[100];
var array = collection.ToArray();
var results = array.Skip(1).Select((e, i) => e - array[i]);

如何更好地实现目标?

4

3 回答 3

2
 var result = Enumerable.Range(1, arrayCollection.Length - 1)
               .Select(i => new[] {arrayCollection[i - 1], arrayCollection[i]});

如果arrayCollectionIEnumerable

var result = Enumerable.Range(1, arrayCollection.Count() - 1)
                 .Select(i => new[] {
                          arrayCollection.ElementAt(i - 1), 
                          arrayCollection.ElementAt(i) 
                        });
于 2013-02-19T08:18:58.170 回答
2

这是另一个:

var ints = Enumerable.Range(0, 10);
var paired = ints.Zip(ints.Skip(1), Tuple.Create);

这样你会得到对 {0,1}, {1,2} ...

我认为这就是您所要求的,因为您的代码示例与您所描述的有点不同... :)

于 2013-02-19T08:20:02.377 回答
2
var array = new string[] { "one", "two", "three" };
var result = Enumerable.Range(1, array.Length - 1)
                        .Select(i => new[] { array[i - 1], array[i] });

这是使用数组而不是元组的@TrustMe 解决方案(只是为了向您展示示例,您不应该接受我的回答):

IEnumerable<string> collection = new string[] { "one", "two", "three" };
var result = collection.Zip(collection.Skip(1), (x,y) => new [] { x, y });

但请记住,如果您不使用按索引访问(使用数组或列表) ,该集合将被枚举两次。


更新这是一个扩展方法,它将与集合一起使用,并且只会枚举一次序列

public static class Extensions
{
    public static IEnumerable<T[]> GetOverlappingPairs<T>(
        this IEnumerable<T> source)
    {
        var enumerator = source.GetEnumerator();
        enumerator.MoveNext();

        var first = enumerator.Current;

        while (enumerator.MoveNext())
        {
            var second = enumerator.Current;
            yield return new T[] { first, second };
            first = second;
        }
    }
}

用法:

var result = collection.GetOverlappingPairs();
于 2013-02-19T08:28:43.677 回答