将数组拆分为数组数组

sha*_*are 0 .net c# linq

有一个数组:

var arr = new int[] { 1, 1, 2, 6, 6, 7, 1, 1, 0 };
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法将其拆分为相同值的数组?

var arrs = new int[][] { 
            new int[] { 1, 1 },
            new int[] { 2 },
            new int[] { 6, 6 },
            new int[] { 7 }, 
            new int[] { 1, 1 }, 
            new int[] { 0 } };
Run Code Online (Sandbox Code Playgroud)

我更喜欢linq解决方案但是第一次找不到它.

L.B*_*L.B 5

我会写一个扩展方法:

public static class SOExtensions
{
    public static IEnumerable<IEnumerable<T>> GroupSequenceWhile<T>(this IEnumerable<T> seq, Func<T, T, bool> condition) 
    {
        List<T> list = new List<T>();
        using (var en = seq.GetEnumerator())
        {
            if (en.MoveNext())
            {
                var prev = en.Current;
                list.Add(en.Current);

                while (en.MoveNext())
                {
                    if (condition(prev, en.Current))
                    {
                        list.Add(en.Current);
                    }
                    else
                    {
                        yield return list;
                        list = new List<T>();
                        list.Add(en.Current);
                    }
                    prev = en.Current;
                }

                if (list.Any())
                    yield return list;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并用它作为

var arr = new int[] { 1, 1, 2, 6, 6, 7, 1, 1, 0 };
var result = arr.GroupSequenceWhile((x, y) => x == y).ToList();
Run Code Online (Sandbox Code Playgroud)