2010-08-18 13 views
17

Qual è il modo migliore per raggruppare un array in un elenco di array di n elementi ciascuno in C# 4.Come dividere un array in un gruppo di n elementi ciascuno?

es

string[] testArray = { "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8" }; 

dovrebbe essere diviso in se prendiamo n = 3.

string[] A1 = {"s1", "s2", "s3"}; 
string[] A2 = {"s4", "s5", "s6"}; 
string[] A3 = {"s7", "s8"}; 

Può essere un modo semplice con LINQ?

risposta

23

Ciò genera una serie di matrici di stringhe aventi 3 elementi:

int i = 0; 
var query = from s in testArray 
      let num = i++ 
      group s by num/3 into g 
      select g.ToArray(); 
var results = query.ToArray(); 
+1

+1, l'unico lato negativo di questo approccio è che è valutato con entusiasmo. L'intera query deve essere elaborata prima di poter restituire un singolo elemento. – JaredPar

+0

@JaredPar: punto ben preso; tuttavia, a seconda delle dimensioni della raccolta o della natura dell'elaborazione, la valutazione lenta può essere sopravvalutata. Anche così, +1 alla tua soluzione per fornire un approccio pigro valido. – kbrimington

9

Non penso che ci sia un ottimo metodo integrato per questo, ma si potrebbe scrivere uno come il seguente.

public static IEnumerable<IEnumerable<T>> GroupInto<T>(
    this IEnumerable<T> source, 
    int count) { 

    using (var e = source.GetEnumerator()) { 
    while (e.MoveNext()) { 
     yield return GroupIntoHelper(e, count); 
    } 
    }  
} 

private static IEnumerable<T> GroupIntoHelper<T>(
    IEnumerator<T> e, 
    int count) { 

    do { 
    yield return e.Current; 
    count--; 
    } while (count > 0 && e.MoveNext()); 
} 
+0

Risposta perfetta. Ma dovrebbe fornire un esempio di come risolve il problema nella domanda. –

2

Se è effettivamente array che si sta lavorando anziché IEnumerables generale, e specialmente se gli array sono molto grandi, allora questo metodo è un modo molto veloce e di memoria efficace per farlo. Se vuoi davvero una dichiarazione LINQ, allora non importa.

private static T[][] SliceArray<T>(T[] source, int maxResultElements) 
    { 
     int numberOfArrays = source.Length/maxResultElements; 
     if (maxResultElements * numberOfArrays < source.Length) 
      numberOfArrays++; 
     T[][] target = new T[numberOfArrays][]; 
     for (int index = 0; index < numberOfArrays; index++) 
     { 
      int elementsInThisArray = Math.Min(maxResultElements, source.Length - index * maxResultElements); 
      target[index] = new T[elementsInThisArray]; 
      Array.Copy(source, index * maxResultElements, target[index], 0, elementsInThisArray); 
     } 
     return target; 
    } 
5
int size = 3; 
var results = testArray.Select((x, i) => new { Key = i/size, Value = x }) 
         .GroupBy(x => x.Key, x => x.Value, (k, g) => g.ToArray()) 
         .ToArray(); 

Se non ti dispiace i risultati essere digitati come IEnumerable<IEnumerable<T>> piuttosto che T[][] allora è possibile omettere il ToArray chiamate del tutto:

int size = 3; 
var results = testArray.Select((x, i) => new { Key = i/size, Value = x }) 
         .GroupBy(x => x.Key, x => x.Value); 
1

È possibile utilizzare questa estensione

public static class Extension 
{ 
    private static IEnumerable<TList> Split<TList, T>(this TList value, int countOfEachPart) where TList : IEnumerable<T> 
    { 
     int cnt = value.Count()/countOfEachPart; 
     List<IEnumerable<T>> result = new List<IEnumerable<T>>(); 
     for (int i = 0; i <= cnt; i++) 
     { 
      IEnumerable<T> newPart = value.Skip(i * countOfEachPart).Take(countOfEachPart).ToArray(); 
      if (newPart.Any()) 
       result.Add(newPart); 
      else 
       break; 
     } 

     return result.Cast<TList>(); 
    } 

    public static IEnumerable<IDictionary<TKey, TValue>> Split<TKey, TValue>(this IDictionary<TKey, TValue> value, int countOfEachPart) 
    { 
     IEnumerable<Dictionary<TKey, TValue>> result = value.ToArray() 
                  .Split(countOfEachPart) 
                  .Select(p => p.ToDictionary(k => k.Key, v => v.Value)); 
     return result; 
    } 

    public static IEnumerable<IList<T>> Split<T>(this IList<T> value, int countOfEachPart) 
    { 
     return value.Split<IList<T>, T>(countOfEachPart); 
    } 

    public static IEnumerable<T[]> Split<T>(this T[] value, int countOfEachPart) 
    { 
     return value.Split<T[], T>(countOfEachPart); 
    } 

    public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> value, int countOfEachPart) 
    { 
     return value.Split<IEnumerable<T>, T>(countOfEachPart); 
    } 
} 
Problemi correlati