2016-07-21 174 views
2

我有一個200個元素的數組,我試圖通過爲每N個元素進行分割該數組成爲更小的數組,這意味着我不能使用.take/.skip命令,我已經嘗試了目前自己不同的解決方案爲:每個N元素的新數組

一個的Parallel.For和parallel.foreach(這將是最好的,如果我能明白這一點)

,並與正常和foreach循環,但我現在所能做的就是創建一個新組的自動化解決方案,我自己在arrEtikets中使用了N個元素

string[] arrEtikets = Directory.GetFiles(""); 

public string[] Group2() 
    { 
     arrEtikets.Skip(arrEtikets.Length/10); 
     return arrEtikets.Take(arrEtikets.Length/10).ToArray(); 
    } 
+0

不要ü想要的數組一陽? –

+1

爲什麼你不能使用'Skip'? – user3185569

+1

清楚地說明你的問題。 Directory.GetFiles()可以很慢,是問題的核心嗎?因爲大家都在無視這一點。你是在數組上而不是在List <>上出售的? –

回答

1

可以使用的LINQ通過使用GroupBy沒有SkipTake塊大小到您的陣列被劃分到陣列的列表:

private static List<T[]> SplitToChunks<T>(T[] sequence, int chunkSize) 
{ 
    return sequence.Select((item, index) => new { Index = index, Item = item }) 
        .GroupBy(item => item.Index/chunkSize) 
        .Select(itemPerPage => itemPerPage.Select(v => v.Item).ToArray()) 
        .ToList(); 
} 

用法:

string[] arr = Enumerable.Range(0, 1000).Select(x=> x.ToString()).ToArray(); 

var result = SplitToChunks(arr, 101); 
+0

這實際上是我正在尋找,謝謝 – Pilsneren

+0

但我在哪裏插入我的數據數組以供它使用,它是那麼容納所有我的數組的SplitToChunks列表? – Pilsneren

+0

@Pilsneren'result'包含所有數組的列表。你可以循環結果 – user3185569

2

典型Skip + Take溶液可以是像這樣:

public static IEnumerable<T[]> SplitArrayWithLinq<T>(T[] source, int size) { 
    if (null == source) 
    throw new ArgumentNullException("source"); 
    else if (size <= 0) 
    throw new ArgumentOutOfRangeException("size", "size must be positive"); 

    return Enumerable 
    .Range(0, source.Length/size + (source.Length % size > 0 ? 1 : 0)) 
    .Select(index => source 
     .Skip(size * index) 
     .Take(size) 
     .ToArray()); 
} 

如果您不允許使用的LINQSkip以及Take包括):

public static IEnumerable<T[]> SplitArray<T>(T[] source, int size) { 
    if (null == source) 
    throw new ArgumentNullException("source"); 
    else if (size <= 0) 
    throw new ArgumentOutOfRangeException("size", "size must be positive"); 

    int n = source.Length/size + (source.Length % size > 0 ? 1 : 0); 

    for (int i = 0; i < n; ++i) { 
    T[] item = new T[i == n - 1 ? source.Length - size * i : size]; 

    Array.Copy(source, i * size, item, 0, item.Length); 

    yield return item; 
    } 
} 

測試(讓我們分裂[1, 2, ... 8, 9]陣列爲4項目組塊):

var source = Enumerable.Range(1, 9).ToArray(); 

var result = SplitArray(source, 4); 

string report = String.Join(Environment.NewLine, 
    result.Select(item => String.Join(", ", item))); 

// 1, 2, 3, 4 
// 5, 6, 7, 8 
// 9   // <- please, notice that the last chunk has 1 item only 
Console.Write(report); 
相關問題