Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New array for each N element

Tags:

arrays

c#

I have an array of 200~ elements and i'm trying to split that array into smaller arrays by doing it for each N amount of elements, meaning i cannot use the .take / .skip commands, i have currently tried myself with different solutions as:

a Parallel.for and parallel.foreach (Which would be the best if i could figure that out)

and with the normal for and foreach loops, but stuck at the moment, where all i can do is this static solution of creating a new group myself foreach N amount of elements in the arrEtikets

string[] arrEtikets = Directory.GetFiles("");

public string[] Group2()
    {
        arrEtikets.Skip(arrEtikets.Length / 10);
        return arrEtikets.Take(arrEtikets.Length / 10).ToArray();
    }
like image 574
Pilsneren Avatar asked Jul 28 '26 11:07

Pilsneren


1 Answers

You can use Linq to split your array to a list of arrays by chunk size using GroupBy with no Skip or Take :

private static List<T[]> SplitToChunks<T>(T[] sequence, int chunkSize)
{
    return sequence.Select((item, index) => new { Index = index, Item = item })
                    .GroupBy(item => item.Index / chunkSize)
                    .Select(itemPerPage => itemPerPage.Select(v => v.Item).ToArray())
                    .ToList();
}

Usage:

string[] arr = Enumerable.Range(0, 1000).Select(x=> x.ToString()).ToArray();

var result = SplitToChunks(arr, 101);
like image 104
Zein Makki Avatar answered Jul 30 '26 01:07

Zein Makki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!