2011-06-10 132 views
0

這是我從數據庫讀取到數據表中的數據。LINQ訂購分組數據

enter image description here

的數據表稱爲表現重塑。

對於每個相同/不同的UnitType + UnitZoom + MemberZoom,我創建一個新的Unit並將MemberId讀入MemberListId中 - 這應發生在由MemberOrder的編號給定的順序中。示例數據:

1單元:ABC - > P1,P2
UNIT2:1 2 3 - > P9,P12,P4
UNIT3:H23 B10 T15 - > X4,T5,Z3,Y1

我現在是不正確的排序代碼:

var groupedCollection = table.AsEnumerable() 
             .GroupBy(row => new 
             { 
              UType = row.Field<string>("UnitType"), 
              UZoom = row.Field<string>("UnitZoom"), 
              MZoom = row.Field<string>("MemberZoom"), 
              MOrder = row.Field<int>("MemberOrder"), 
    // I DO NOT WANT the MemberOrder to be in the Group Key, but later on I use this Property to order by it... 
             });   


       var unitCollection = groupedCollection 
            .Select(g => new Unit 
            { 
             UnitType = g.Key.UType, 
             UnitZoom = g.Key.UZoom, 
             MemberZoom = g.Key.MZoom,         
             MemberIdList = g.Select(r => r.Field<string>("MemberId")).OrderBy(b => g.Key.MOrder).ToList(), 
            }); 

       List<Unit> units = unitCollection.ToList(); 

回答

1

其訂購的靜態值列表:

MemberIdList = g.Select(r => r.Field<string>("MemberId")).OrderBy(b => g.Key.MOrder).ToList() 

ü應該使用事端摹這樣的:OrderBy(b => b.SomeValue)

它應該是這樣的:

var groupedCollection = table.AsEnumerable() 
            .GroupBy(row => new 
            { 
             UType = row.Field<string>("UnitType"), 
             UZoom = row.Field<string>("UnitZoom"), 
             MZoom = row.Field<string>("MemberZoom") 
            });   


      var unitCollection = groupedCollection 
           .Select(g => new Unit 
           { 
            UnitType = g.Key.UType, 
            UnitZoom = g.Key.UZoom, 
            MemberZoom = g.Key.MZoom,         
            MemberIdList = g.OrderBy(b => b.Field<int>("MemberOrder").Select(r => r.Field<string>("MemberId")).ToList(), 
           }); 

      List<Unit> units = unitCollection.ToList();