如何将数组拆分为特定大小的块

如何将数组拆分为特定大小的块

本文介绍了如何将数组拆分为特定大小的块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下午

我需要将数组拆分为较小的块".

I need to split an array into smaller "chunks".

我要传递大约1200多个项目,并且需要将它们拆分成更容易处理的数组,每个数组包含100个项目,然后我需要对其进行处理.

I am passing over about 1200 items, and need to split these into easier to handle arrays of 100 items each, which I then need to process.

任何人都可以提出一些建议吗?

Could anyone please make some suggestions?

推荐答案

您可以使用 LINQ 将所有项目按块大小分组,然后再创建新的数组.

You can use LINQ to group all items by the chunk size and create new Arrays afterwards.

// build sample data with 1200 Strings
string[] items = Enumerable.Range(1, 1200).Select(i => "Item" + i).ToArray();
// split on groups with each 100 items
String[][] chunks = items
                    .Select((s, i) => new { Value = s, Index = i })
                    .GroupBy(x => x.Index / 100)
                    .Select(grp => grp.Select(x => x.Value).ToArray())
                    .ToArray();

for (int i = 0; i < chunks.Length; i++)
{
    foreach (var item in chunks[i])
        Console.WriteLine("chunk:{0} {1}", i, item);
}

请注意,没有必要创建新的数组(需要CPU周期和内存).省略两个 ToArrays 时,也可​​以使用 IEnumerable< IEnumerable< String>> .

Note that it's not necessary to create new arrays(needs cpu cycles and memory). You could also use the IEnumerable<IEnumerable<String>> when you omit the two ToArrays.

这是正在运行的代码: http://ideone.com/K7Hn2

Here's the running code: http://ideone.com/K7Hn2

这篇关于如何将数组拆分为特定大小的块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 04:05