下午,
我需要将数组拆分为更小的“块”。
我传递了大约 1200 个项目,需要将它们拆分为更易于处理的数组,每个数组包含 100 个项目,然后我需要对其进行处理。
任何人都可以提出一些建议吗?
Array.Copy 自 1.1 以来就已经存在,并且在分块数组方面做得非常出色。
string[] buffer;
for(int i = 0; i < source.Length; i+=100)
{
buffer = new string[100];
Array.Copy(source, i, buffer, 0, 100);
// process array
}
并对其进行扩展:
public static class Extensions
{
public static T[] Slice<T>(this T[] source, int index, int length)
{
T[] slice = new T[length];
Array.Copy(source, index, slice, 0, length);
return slice;
}
}
并使用扩展:
string[] source = new string[] { 1200 items here };
// get the first 100
string[] slice = source.Slice(0, 100);
更新:我认为您可能不希望ArraySegment<>
进行性能检查,因为它只是使用原始数组作为其源并维护一个 Offset 和 Count 属性来确定“段”。不幸的是,没有办法将段作为数组检索,所以有些人已经为它编写了包装器,比如这里:ArraySegment - Returning the actual segment C#
ArraySegment<string> segment;
for (int i = 0; i < source.Length; i += 100)
{
segment = new ArraySegment<string>(source, i, 100);
// and to loop through the segment
for (int s = segment.Offset; s < segment.Array.Length; s++)
{
Console.WriteLine(segment.Array[s]);
}
}
测试方法(在Release模式下):
static void Main(string[] args)
{
string[] source = new string[1000000];
for (int i = 0; i < source.Length; i++)
{
source[i] = "string " + i.ToString();
}
string[] buffer;
Console.WriteLine("Starting stop watch");
Stopwatch sw = new Stopwatch();
for (int n = 0; n < 5; n++)
{
sw.Reset();
sw.Start();
for (int i = 0; i < source.Length; i += 100)
{
buffer = new string[100];
Array.Copy(source, i, buffer, 0, 100);
}
sw.Stop();
Console.WriteLine("Array.Copy: " + sw.ElapsedMilliseconds.ToString());
sw.Reset();
sw.Start();
for (int i = 0; i < source.Length; i += 100)
{
buffer = new string[100];
buffer = source.Skip(i).Take(100).ToArray();
}
sw.Stop();
Console.WriteLine("Skip/Take: " + sw.ElapsedMilliseconds.ToString());
sw.Reset();
sw.Start();
String[][] chunks = source
.Select((s, i) => new { Value = s, Index = i })
.GroupBy(x => x.Index / 100)
.Select(grp => grp.Select(x => x.Value).ToArray())
.ToArray();
sw.Stop();
Console.WriteLine("LINQ: " + sw.ElapsedMilliseconds.ToString());
}
Console.ReadLine();
}
结果(以毫秒为单位):
Array.Copy: 15
Skip/Take: 42464
LINQ: 881
Array.Copy: 21
Skip/Take: 42284
LINQ: 585
Array.Copy: 11
Skip/Take: 43223
LINQ: 760
Array.Copy: 9
Skip/Take: 42842
LINQ: 525
Array.Copy: 24
Skip/Take: 43134
LINQ: 638
您可以使用LINQ
按块大小对所有项目进行分组,然后创建新数组。
// 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 周期和内存)。IEnumerable<IEnumerable<String>>
当你省略这两个时,你也可以使用ToArrays
。
这是运行代码:http: //ideone.com/K7Hn2
在这里,我找到了另一个 linq 解决方案:
int[] source = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int i = 0;
int chunkSize = 3;
int[][] result = source.GroupBy(s => i++ / chunkSize).Select(g => g.ToArray()).ToArray();
//result = [1,2,3][4,5,6][7,8,9]
您可以使用Skip()
和Take()
string[] items = new string[]{ "a", "b", "c"};
string[] chunk = items.Skip(1).Take(1).ToArray();
string[] amzProductAsins = GetProductAsin();;
List<string[]> chunks = new List<string[]>();
for (int i = 0; i < amzProductAsins.Count; i += 100)
{
chunks.Add(amzProductAsins.Skip(i).Take(100).ToArray());
}
您可以使用List.GetRange:
for(var i = 0; i < source.Count; i += chunkSize)
{
List<string> items = source.GetRange(i, Math.Min(chunkSize, source.Count - i));
}
虽然不如 Array.Copy 快,但我认为它看起来更干净:
var list = Enumerable.Range(0, 723748).ToList();
var stopwatch = new Stopwatch();
for (int n = 0; n < 5; n++)
{
stopwatch.Reset();
stopwatch.Start();
for(int i = 0; i < list.Count; i += 100)
{
List<int> c = list.GetRange(i, Math.Min(100, list.Count - i));
}
stopwatch.Stop();
Console.WriteLine("List<T>.GetRange: " + stopwatch.ElapsedMilliseconds.ToString());
stopwatch.Reset();
stopwatch.Start();
for (int i = 0; i < list.Count; i += 100)
{
List<int> c = list.Skip(i).Take(100).ToList();
}
stopwatch.Stop();
Console.WriteLine("Skip/Take: " + stopwatch.ElapsedMilliseconds.ToString());
stopwatch.Reset();
stopwatch.Start();
var test = list.ToArray();
for (int i = 0; i < list.Count; i += 100)
{
int length = Math.Min(100, list.Count - i);
int[] c = new int[length];
Array.Copy(test, i, c, 0, length);
}
stopwatch.Stop();
Console.WriteLine("Array.Copy: " + stopwatch.ElapsedMilliseconds.ToString());
stopwatch.Reset();
stopwatch.Start();
List<List<int>> chunks = list
.Select((s, i) => new { Value = s, Index = i })
.GroupBy(x => x.Index / 100)
.Select(grp => grp.Select(x => x.Value).ToList())
.ToList();
stopwatch.Stop();
Console.WriteLine("LINQ: " + stopwatch.ElapsedMilliseconds.ToString());
}
以毫秒为单位的结果:
List<T>.GetRange: 1
Skip/Take: 9820
Array.Copy: 1
LINQ: 161
List<T>.GetRange: 9
Skip/Take: 9237
Array.Copy: 1
LINQ: 148
List<T>.GetRange: 5
Skip/Take: 9470
Array.Copy: 1
LINQ: 186
List<T>.GetRange: 0
Skip/Take: 9498
Array.Copy: 1
LINQ: 110
List<T>.GetRange: 8
Skip/Take: 9717
Array.Copy: 1
LINQ: 148
使用 LINQ,可以使用 Take() 和 Skip() 函数
通用递归扩展方法:
public static IEnumerable<IEnumerable<T>> SplitList<T>(this IEnumerable<T> source, int maxPerList)
{
var enumerable = source as IList<T> ?? source.ToList();
if (!enumerable.Any())
{
return new List<IEnumerable<T>>();
}
return (new List<IEnumerable<T>>() { enumerable.Take(maxPerList) }).Concat(enumerable.Skip(maxPerList).SplitList<T>(maxPerList));
}
如果您有一个要划分的数组,但通过这个简单的解决方案,您可以将缺少的元素平等地共享到各个“块”中。
int[] arrInput = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
var result = SplitArrey(arrInput, 5);
foreach (var item in result) {
Console.WriteLine(" {0}", String.Join(" ", item));
}
功能是:
public static List<int[]> SplitArrey(int[] arrInput, int nColumn) {
List<int[]> result = new List<int[]>(nColumn);
int itemsForColum = arrInput.Length / nColumn;
int countSpareElement = arrInput.Length - (itemsForColum * nColumn);
// Add and extra space for the spare element
int[] newColumLenght = new int[nColumn];
for (int i = 0; i < nColumn; i++)
{
int addOne = (i < countSpareElement) ? 1 : 0;
newColumLenght[i] = itemsForColum + addOne;
result.Add(new int[itemsForColum + addOne]);
}
// Copy the values
int offset = 0;
for (int i = 0; i < nColumn; i++)
{
int count_items_to_copy = newColumLenght[i];
Array.Copy(arrInput, offset, result[i], 0, count_items_to_copy);
offset += newColumLenght[i];
}
return result;
}
结果是:
1 2 3
4 5 6
7 8
9 10
11 12