拆分数组的最佳方法 [英] Best way to split an array

查看:92
本文介绍了拆分数组的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下午, 我需要找出将数组拆分为较小的块"的最佳方法是什么.

Afternoon, I need to find out what the best way to split an array into smaller "chunks" would be.

我要传递大约1200多个项目,并且需要将它们分成更容易处理的100个组,然后我需要将它们传递给处理.

I am passing over about 1200 items, and need to split these into easier to handle groups of 100, then i need to pass them over to processed.

有人可以提出一些建议吗?

Could any one 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

这篇关于拆分数组的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆