2013-09-24 13 views
16

Ho una lista di byte e voglio dividere questa lista in parti più piccole.C#: divisione di una matrice in n parti

var array = new List<byte> {10, 20, 30, 40, 50, 60}; 

Questa lista ha 6 celle. Ad esempio, voglio dividerlo in 3 parti contenenti ogni 2 byte.

Ho provato a scrivere alcuni loop e ho utilizzato array 2D per raggiungere il mio scopo ma non so che sia un approccio corretto.

  byte[,] array2D = new byte[window, lst.Count/window]; 
      var current = 0; 
      for (int i = 0; i < rows; i++) 
      { 
       for (int j = 0; j < cols; j++) 
       { 
        array2D[i, j] = lst[current++]; 
       } 
      } 
+0

come circa il tuo codice? sembra che funzioni, anche se 'rows' e' cols' non sono ancora chiari qui. il 'rows' dovrebbe essere' window' e 'cols' dovrebbe essere' lst.Count/window'. –

+0

Utilizzare il batch morelinq https://code.google.com/p/morelinq/source/browse/MoreLinq/Batch.cs –

risposta

33

Un buon modo sarebbe creare un metodo generico/di estensione per dividere qualsiasi array. Questo è mio:

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

Inoltre, questa soluzione è differita. Quindi, chiama semplicemente split(size) sul tuo array.

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

Come richiesto, ecco un metodo/estensione generico per ottenere un array 2D quadrati da un array:

public static T[,] ToSquare2D<T>(this T[] array, int size) 
{ 
    var buffer = new T[(int)Math.Ceiling((double)array.Length/size), size]; 
    for (var i = 0; i < (float)array.Length/size; i++) 
    { 
     for (var j = 0; j < size; j++) 
     { 
      buffer[i, j] = array[i + j]; 
     } 
    } 
    return buffer; 
} 

Buon divertimento :)

+0

Questo ** modifica ** la struttura dati desiderata dell'OP ** totalmente **. Vuole 'array 2D quadrati '. –

+0

Non proprio. I suoi "array 2D quadrati" sono un approccio che ha cercato di risolvere, non quello che vuole ottenere. L'uso di 'IEnumerable >' è molto più flessibile. – ZenLulz

+0

Ovviamente, sceglierei qualcosa come "IEnumerable stuff" o "List stuff". Ma sembra essere ciò che l'OP vuole. Non puoi essere così sicuro. Infatti se fai qualche calcolo con 'Matrix', usare' array 2D quadrati 'sarebbe meglio. –

8

utilizzando Linq

public List<List<byte>> SplitToSublists(List<byte> source) 
{ 
    return source 
      .Select((x, i) => new { Index = i, Value = x }) 
      .GroupBy(x => x.Index/100) 
      .Select(x => x.Select(v => v.Value).ToList()) 
      .ToList(); 
} 

semplicemente lo usano

var sublists = SplitToSublists(lst); 
0

Si potrebbe desiderare di dare una prova.

var bytes = new List<byte>(10000); 
int size = 100; 
var lists = new List<List<byte>>(size); 
for (int i = 0; i < bytes.Count; i += size) 
{ 
     var list = new List<byte>(); 
     list.AddRange(bytes.GetRange(i, size)); 
     lists.Add(list); 
} 
+1

Questo fallisce e va fuori limite; è necessario sostituire "GetRange (i, size)" con "GetRange (i, Math.Min (size, bytes.Count - i))" – Dan

0

Ecco la mia soluzione naif:

public static string[] SplitArrey(string[] ArrInput, int n_column) 
    { 

     string[] OutPut = new string[n_column]; 
     int NItem = ArrInput.Length; // Numero elementi 
     int ItemsForColum = NItem/n_column; // Elementi per arrey 
     int _total = ItemsForColum * n_column; // Emelemti totali divisi 
     int MissElement = NItem - _total; // Elementi mancanti 

     int[] _Arr = new int[n_column]; 
     for (int i = 0; i < n_column; i++) 
     { 
      int AddOne = (i < MissElement) ? 1 : 0; 
      _Arr[i] = ItemsForColum + AddOne; 
     } 

     int offset = 0; 
     for (int Row = 0; Row < n_column; Row++) 
     { 
      for (int i = 0; i < _Arr[Row]; i++) 
      { 
       OutPut[Row] += ArrInput[i + offset] + " "; // <- Here to change how the strings are linked 
      } 
      offset += _Arr[Row]; 
     } 
     return OutPut; 
    } 
Problemi correlati