简单的LINQ查询

时间:2010-09-21 21:48:22

标签: linq

我有一个X项目列表。我想要LINQ查询将其转换为批次(列表列表),其中每个批次有4个项目,除了最后一个可以有1-4(无论剩下的是什么)。此外,数字4应该是可配置的,因此它可以是5,17等。

谁能告诉我怎么写呢?

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

提前谢谢!

3 个答案:

答案 0 :(得分:4)

如果您对输入的结果IEnumerable<IEnumerable<T>>感到满意,那么您可以这样做:

int groupSize = 4;

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

如果您想要实际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,
                                (k, g) => g.ToList())
                       .ToList();

答案 1 :(得分:0)

Here是关于使用TakeSkip进行分页的好文章,这与您请求的功能相同。它不会让你一路走到LINQ的一行,但希望有所帮助。

答案 2 :(得分: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);