2012-10-21 33 views
-2

有一個List,SomeObject具有屬性TargetObject。 我需要的是創建一個List,其中SomeObjects具有以下TargetObject。通過參數排序收集LINQ查詢

SO_1(TO_1)| SO_2(TO_2)| SO_3(TO_3)| SO_4(TO_1)| SO_5(TO_1)| SO_6(TO_1)| SO_7(TO_1)| SO_8(TO_2)| SO_9(TO_2)| SO_10(TO_4)

必須變成

SO_1(TO_1)| SO_2(TO_2)| SO_3(TO_3)| SO_10(TO_4)| SO_4(TO_1)| SO_8(TO_2)| SO_6(TO_1)| SO_9(TO_2)| SO_7(TO_1)| SO_5(TO_1)

最後我想運行MaxDegreeOfParallelism = 5的Parallel.ForEach(List),所以每個5個項目的循環都不會同時擁有相同的TargetObject。

感謝

+2

您能否重新說明您的問題? – Rockstart

+0

我對改寫不好,從...收集是我可以做出的最好的解釋,對不起。 – eugeneK

回答

0

這是我用於不同目的的InterlaceBy擴展方法但它似乎適用於您的情況。

List<int> list = new List<int>() {1,2,3,1,1,1,1,2,2,4 }; //your TO's 
var newlist = list.InterlaceBy(x => x).ToList(); //1,2,3,4,1,2,1,2,1,1 

public static partial class MyExtensions 
{ 
    public static IEnumerable<T> InterlaceBy<T, S>(this IEnumerable<T> input, Func<T, S> selector) 
    { 
     return input 
       .GroupBy(selector) 
       .SelectMany(g => g.Select((x, i) => new { key = i, value = x })) 
       .OrderBy(x => x.key) 
       .Select(x => x.value); 
    } 
} 
+1

謝謝你的理解 – eugeneK

1

最簡單的方式做到這一點(至少我能想到的最簡單的)是由TargetObject首先對它們進行排序,然後將它們按TargetObject,重建你使用每組的一個元素集合在一時間。

List<SomeObject> CustomSort(List<SomeObject> list) 
{ 

    var ordered = list.OrderBy(x => x.TargetObject); // might not be necessary. Not sure if group by orders the group or not. 
    var groups = ordered.GroupBy(x => x.x.TargetObject); 
    List<SomeObject> res = new List<SomeObject>(); 

    int position = 0; 
    while(res.Count < list.Count) 
    { 
    foreach (var grp in groups) 
    { 
     SomeObject current = grp.ElementAtOrDefault(position); 
     if (current != null) res.Add(current); 
    } 
    position ++; 
    } 
    return res; 
} 

PS:此代碼沒有優化,但僅用於演示此方法。