Splitting an array using LINQ

前端 未结 7 1171
你的背包
你的背包 2020-12-10 15:02

I have a collection uni-dimensional like this:

[1,2,4,5.....n]

I would like to convert that collection in a bi-dimensional collection like

7条回答
  •  渐次进展
    2020-12-10 15:49

    It's not a pure LINQ but it's intended to be used with it:

    public static class MyEnumerableExtensions
    {
        public static IEnumerable Split(this IEnumerable source, int size)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source can't be null.");
            }
    
            if (size == 0)
            {
                throw new ArgumentOutOfRangeException("Chunk size can't be 0.");
            }
    
            List result = new List(size);
            foreach (T x in source)
            {
                result.Add(x);
                if (result.Count == size)
                {
                    yield return result.ToArray();
                    result = new List(size);
                }
            }
        }
    }
    

    It can be used from your code as:

    private void Test()
    {
        // Here's your original sequence
        IEnumerable seq = new[] { 1, 2, 3, 4, 5, 6 };
    
        // Here's the result of splitting into chunks of some length 
        // (here's the chunks length equals 3). 
        // You can manipulate with this sequence further, 
        // like filtering or joining e.t.c.
        var splitted = seq.Split(3);
    }
    

提交回复
热议问题