2016-10-11 28 views
1

使用LINQ(或morelinq),如何將未知長度(但小)的數組劃分爲最後具有較小(不均勻)集的偶數集,但在每個列表中維護順序?使用(大部分)等長集

var array = new int[] {1,2,3,4}; var sets = array.something(3); 尋找的結果: {1,2},{3},{4}

{1} -> {1},{},{} 
{1,2} -> {1},{2},{} 
{1,2,3} -> {1},{2},{3} 
{1,2,3,4} -> {1,2},{3},{4} 
{1,2,3,4,5} -> {1,2},{3,4},{5} 
{1,2,3,4,5,6} -> {1,2},{3,4},{5,6} 

我的原代碼:

const int MaxPerColumn = 6; 
var perColumn = (list.Count + columnCount - 1)/columnCount; 
for (var col = 1; col <= columnCount; col++) 
{ 
    var items = list.Skip((col - 1) * columnCount).Take(perColumn).Pad(MaxPerColumn, "").ToList(); 

    // DoSomething 
} 

,沒有工作,因爲它創造了{1,2},{3,4},{}

+0

爲什麼{1,2,3,4}是{1,2},{3},{4}和{1,2,3,4,5,6}是{1,2},{3,4 },{5,6}。該模式並不真正排隊? – Dispersia

+0

我想你應該明確說明你的例子是用來製作3組的。 –

+0

你試過什麼?你的實現有什麼問題? – Servy

回答

1

{1,2,3,4}列表我建議不是在執行使用的LINQ這裏,但IEnumerator<T>,甚至沒有IEnumerable<T>

public static IEnumerable<T[]> Something<T>(this IEnumerable<T> source, int count) { 
    if (null == source) 
    throw new ArgumentNullException("source"); 
    else if (count <= 0) 
    throw new ArgumentOutOfRangeException("count"); 

    int c = source.Count(); 
    int size = c/count + (c % count > 0 ? 1 : 0); 
    int large = count - count * size + c;  

    using (var en = source.GetEnumerator()) { 
    for (int i = 0; i < count; ++i) { 
     T[] chunk = new T[i < large ? size : size - 1]; 

     for (int j = 0; j < chunk.Length; ++j) { 
     en.MoveNext(); 

     chunk[j] = en.Current; 
     } 

     yield return chunk; 
    } 
    } 
} 

....

var array = new int[] { 1, 2, 3, 4 }; 

string result = string.Join(", ", array 
    .Something(5) 
    .Select(item => $"[{string.Join(", ", item)}]")); 

// [1], [2], [3], [4], [] 
Console.Write(result);