C# Splitting An Array

后端 未结 9 1336
情深已故
情深已故 2020-12-10 00:39

I need to split an array of indeterminate size, at the midpoint, into two separate arrays.

The array is generated from a list of strings using ToArray().

<         


        
9条回答
  •  自闭症患者
    2020-12-10 01:25

    I had an issue with Linq's Skip() and Take() functions when dealing with arrays with massive amounts of elements (i.e. byte arrays), where element counts are in the millions.

    This approach dramatically reduced split execute times for me.

    public static IEnumerable> Split(this ICollection self, int chunkSize)
    {
        var splitList = new List>();
        var chunkCount = (int)Math.Ceiling((double)self.Count / (double)chunkSize);
    
        for(int c = 0; c < chunkCount; c++)
        {
            var skip = c * chunkSize;
            var take = skip + chunkSize;
            var chunk = new List(chunkSize);
    
            for(int e = skip; e < take && e < self.Count; e++)
            {
                chunk.Add(self.ElementAt(e));
            }
    
            splitList.Add(chunk);
        }
    
        return splitList;
    }
    

提交回复
热议问题