2010-09-21 215 views
0

我有一個X項目列表。我想要LINQ查詢,將它轉換爲批量(列表清單),其中每個批次有4個項目,除了最後一個可以有1-4(剩餘部分)。此外,數字4應該是可配置的,以便它可以5,17等。簡單的LINQ查詢

誰能告訴我如何寫?

List<Item> myItems = ...; 
List<List<Item>> myBatches = myItems.???? 

預先感謝您!

回答

4

如果你滿意的結果被分類爲IEnumerable<IEnumerable<T>>那麼你可以這樣做:如果你想要一個實際List<List<T>>,那麼你就需要添加一些額外的ToList電話

int groupSize = 4; 

var myBatches = myItems.Select((x, i) => new { Val = x, Idx = i }) 
         .GroupBy(x => x.Idx/groupSize, 
           x => x.Val); 

int groupSize = 4; 

var myBatches = myItems.Select((x, i) => new { Val = x, Idx = i }) 
         .GroupBy(x => x.Idx/groupSize, 
           x => x.Val, 
           (k, g) => g.ToList()) 
         .ToList(); 
0

Here是一篇關於使用TakeSkip進行分頁的好文章,它與您請求的功能相同。它並沒有讓你找到一行LINQ,但希望有所幫助。

0

這讓我想到我們在LINQ之前是如何做到這一點的。

var vessels = new List<Vessel>() 
    { new Vessel() { id = 8, name = "Millennium Falcon" }, 
     new Vessel() { id = 4, name = "Ebon Hawk" }, 
     new Vessel() { id = 34, name = "Virago"}, 
     new Vessel() { id = 12, name = "Naboo royal starship"}, 
     new Vessel() { id = 17, name = "Radiant VII"}, 
     new Vessel() { id = 7, name = "Lambda-class shuttle"}, 
     new Vessel() { id = 23, name = "Rogue Shadow"}}; 

var chunksize=2; 

// With LINQ     
var vesselGroups = vessels.Select((v, i) => new { Vessel = v, Index = i }) 
          .GroupBy(c => c.Index/chunksize, c => c.Vessel, (t,e)=>e.ToList()) 
          .ToList(); 

// Before LINQ (most probably not optimal) 
var groupedVessels = new List<List<Vessel>>(); 
var g = new List<Vessel>(); 
var chunk = chunksize; 
foreach(var vessel in vessels) 
{ 
    g.Add(vessel); 
    chunk--; 
    if (chunk == 0) 
    { 
     groupedVessels.Add(g); 
     g = new List<Vessel>(); 
     chunk = chunksize; 
    } 
} 
groupedVessels.Add(g);