将集合分成较小的集合,但重复项目

Qld*_*bbo 3 c# linq

我无法理解如何做到这一点.

我有一组对象

{ object1, object2, object3, object4 }
Run Code Online (Sandbox Code Playgroud)

我想把这个集合分解成一个集合集合,这样我最终会得到一些看起来像的东西

{ { object1, object2}, {object2, object3}, {object3, object4} }
Run Code Online (Sandbox Code Playgroud)

我已经找到了如何将集合分成较小的集合,但它是每个集合中前一个项目的重复.

任何帮助非常感谢!

我目前的块方法(取自此处的另一个问题)是

    public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> source, int size)
    {
            return source.Select((x, i) => new { Index = i, Value = x })
                        .GroupBy(x => x.Index / size)
                        .Select(x => x.Select(v => v.Value));
    }
Run Code Online (Sandbox Code Playgroud)

编辑 这是有效的,但有更好的方法吗?

    public static ICollection<ICollection<T>> BreakUp<T>(this IEnumerable<T> polylines, int size)
    {
        var results = new Collection<ICollection<T>>();
        results.Add(new Collection<T>());

        var x = 0;
        for (var i = 0; i < polylines.Count(); i++)
        {
            results[x].Add(polylines.ElementAt(i));

            if (results[x].Count() % size == 0 && i != polylines.Count() - 1)
            {
                x++;
                results.Add(new Collection<T>());
                results[x].Add(polylines.ElementAt(i));
            }
        }

        return results;
    }
Run Code Online (Sandbox Code Playgroud)

slo*_*oth 8

您可以像这样简化代码:

public static IEnumerable<IEnumerable<T>> BreakUp<T>(IEnumerable<T> this source, int size)
{
    var max = source.Count();
    int i = 0;
    while (i < max)
    {
        var current = source.Skip(i).Take(size);
        if (current.Count() > 1)
            yield return current;
        i += size -1;
    }
}
Run Code Online (Sandbox Code Playgroud)

测试:

void Main()
{
    Console.WriteLine("Example 1");
    var source = new Int32[] {1, 2, 3, 4, 5};

    foreach (var i in BreakUp(source, 2))
        Console.WriteLine(i);

    Console.WriteLine("Example 2");

    foreach (var i in BreakUp(source, 4))
        Console.WriteLine(i);
}
Run Code Online (Sandbox Code Playgroud)

这是一个source只迭代一次的解决方案:

public static IEnumerable<IEnumerable<T>> BreakUp<T>(IEnumerable<T> this source, int size)
{
    using(var e = source.GetEnumerator())
    {
        T last = default(T);
        bool has_last = false;
        while(e.MoveNext())
        {
            var current = new List<T>(size);
            if(has_last)
                current.Add(last);

            last = (T)e.Current;
            current.Add(last);

            while(current.Count < size && e.MoveNext())
            {
                last = (T)e.Current;
                current.Add(last);
                has_last = true;
            }

            yield return current;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述