簡體   English   中英

C#拆分數組

[英]C# Splitting An Array

我需要在中點將一個不確定大小的數組拆分成兩個獨立的數組。

使用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);
    }
}

}

您可以使用以下方法將數組拆分為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);
}

使用通用拆分方法:

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);
}

我還想添加一個解決方案,將一個數組拆分成幾個包含確定數量單元格的較小數組。

一種不錯的方法是創建一個通用/擴展方法來拆分任何數組。 這是我的:

/// <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);
    }
}

而且,該解決方案被推遲。 然后,只需在數組上調用split(size)

var array = new byte[] {10, 20, 30, 40, 50};
var splitArray = array.Split(2);

玩得開心 :)

在處理具有大量元素(即字節數組)的數組時,我遇到了Linq的Skip()和Take()函數的問題,其中元素數量是數百萬。

這種方法大大減少了我的分割執行時間。

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;
}

如果您沒有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);
}

為什么不分配兩個數組並復制內容?

編輯:你走了:

        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);

你為什么把UList作為參考? 似乎沒有必要。

如果我需要這樣做,我會使用通用的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);
}

我認為您正在尋找的是Array類,特別是Array.Copy靜態方法。 如果C#數組有方法,您可以將該類視為包含將成為數組實例方法的方法。

如果關注功能范例,這可能會有所幫助:

   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);
     }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM