C# 拆分数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1841246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Splitting An Array
提问by TheValheruGod
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().
该数组是使用 ToArray() 从字符串列表生成的。
public void AddToList ()
{
bool loop = true;
string a = "";
Console.WriteLine("Enter a string value and press enter to add it to the list");
while (loop == true)
{
a = Console.ReadLine();
if (a != "")
{
mylist.Add(a);
}
else
{
loop = false;
}
}
}
public void ReturnList()
{
string x = "";
foreach (string number in mylist)
{
x = x + number + " ";
}
Console.WriteLine(x);
Console.ReadLine();
}
}
class SplitList
{
public string[] sTop;
public string[] sBottom;
public void Split(ref UList list)
{
string[] s = list.mylist.ToArray();
//split the array into top and bottom halfs
}
}
static void Main(string[] args)
{
UList list = new UList();
SplitList split = new SplitList();
list.AddToList();
list.ReturnList();
split.Split(ref list);
}
}
}
}
采纳答案by JaredPar
You could use the following method to split an array into 2 separate arrays
您可以使用以下方法将数组拆分为 2 个单独的数组
public void Split<T>(T[] array, int index, out T[] first, out T[] second) {
first = array.Take(index).ToArray();
second = array.Skip(index).ToArray();
}
public void SplitMidPoint<T>(T[] array, out T[] first, out T[] second) {
Split(array, array.Length / 2, out first, out second);
}
回答by BlueTrin
Why don't you allocate two arrays and copy the contents ?
为什么不分配两个数组并复制内容?
EDIT: here you go:
编辑:给你:
String[] origin = new String[4];
origin[0] = "zero";
origin[1] = "one";
origin[2] = "two";
origin[3] = "three";
Int32 topSize = origin.Length / 2;
Int32 bottomSize = origin.Length - topSize;
String[] sTop = new String[topSize];
String[] sBottom = new String[bottomSize];
Array.Copy(origin, sTop, topSize);
Array.Copy(origin, topSize , sBottom, 0, bottomSize);
回答by Cecil Has a Name
Use a generic split method:
使用通用拆分方法:
public static void Split<T>(T[] source, int index, out T[] first, out T last)
{
int len2 = source.Length - index;
first = new T[index];
last = new T[len2];
Array.Copy(source, 0, first, 0, index);
Array.Copy(source, index, last, 0, len2);
}
回答by Adam Robinson
Why are you passing the UListas ref? There doesn't appear to be a need for that.
你为什么要通过UListas ref ?似乎没有这个必要。
I would use a generic Splitmethod if I needed to do this:
Split如果我需要这样做,我会使用通用方法:
public void Split<T>(T[] array, out T[] left, out T[] right)
{
left = new T[array.Length / 2];
right = new T[array.Length - left.Length];
Array.Copy(array, left, left.Length);
Array.Copy(array, left.Length, right, 0, right.Length);
}
回答by Nate C-K
I think what you're looking for is the Arrayclass, specifically the Array.Copystatic method. You can think of that class as containing the methods that would be instance methods of arrays if C# arrays had methods.
我认为您正在寻找的是Array类,特别是Array.Copy静态方法。如果 C# 数组有方法,您可以认为该类包含将成为数组实例方法的方法。
回答by Mark Byers
If you don't have Linq, you can use Array.Copy:
如果你没有 Linq,你可以使用 Array.Copy:
public void Split(ref UList list)
{
string[] s = list.mylist.ToArray();
//split the array into top and bottom halfs
string[] top = new string[s.Length / 2];
string[] bottom = new string[s.Length - s.Length / 2];
Array.Copy(s, top, top.Length);
Array.Copy(s, top.Length, bottom, 0, bottom.Length);
Console.WriteLine("Top: ");
foreach (string item in top) Console.WriteLine(item);
Console.WriteLine("Bottom: ");
foreach (string item in bottom) Console.WriteLine(item);
}
回答by ZenLulz
I also want to add a solution to split an array into several smaller arrays containing a determined number of cells.
我还想添加一个解决方案,将数组拆分为几个包含确定数量单元格的较小数组。
A nice way would be to create a generic/extension method to split any array. This is mine:
一个不错的方法是创建一个通用/扩展方法来拆分任何数组。这是我的:
/// <summary>
/// Splits an array into several smaller arrays.
/// </summary>
/// <typeparam name="T">The type of the array.</typeparam>
/// <param name="array">The array to split.</param>
/// <param name="size">The size of the smaller arrays.</param>
/// <returns>An array containing smaller arrays.</returns>
public static IEnumerable<IEnumerable<T>> Split<T>(this T[] array, int size)
{
for (var i = 0; i < (float)array.Length / size; i++)
{
yield return array.Skip(i * size).Take(size);
}
}
Moreover, this solution is deferred. Then, simply call split(size)on your array.
此外,该解决方案被推迟。然后,只需调用split(size)您的数组。
var array = new byte[] {10, 20, 30, 40, 50};
var splitArray = array.Split(2);
Have fun :)
玩得开心 :)
回答by Hyman
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.
在处理包含大量元素(即字节数组)的数组时,我遇到了 Linq 的 Skip() 和 Take() 函数的问题,其中元素数以百万计。
This approach dramatically reduced split execute times for me.
这种方法大大减少了我的分割执行时间。
public static IEnumerable<IEnumerable<T>> Split<T>(this ICollection<T> self, int chunkSize)
{
var splitList = new List<List<T>>();
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<T>(chunkSize);
for(int e = skip; e < take && e < self.Count; e++)
{
chunk.Add(self.ElementAt(e));
}
splitList.Add(chunk);
}
return splitList;
}
回答by Carlos Alberto Flores Onofre
If functional paradigm is a concern, this might help:
如果功能范式是一个问题,这可能会有所帮助:
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> seq, Int32 sizeSplits) {
Int32 numSplits = (seq.Count() / sizeSplits) + 1;
foreach ( Int32 ns in Enumerable.Range(start: 1, count: numSplits) ) {
(Int32 start, Int32 end) = GetIndexes(ns);
yield return seq.Where((_, i) => (start <= i && i <= end));
}
(Int32 start, Int32 end) GetIndexes(Int32 numSplit) {
Int32 indBase1 = numSplit * sizeSplits;
Int32 start = indBase1 - sizeSplits;
Int32 end = indBase1 - 1;
return (start, end);
}
}

