C# Linq 每次迭代选择 5 个项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11427413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:50:27  来源:igfitidea点击:

Linq Select 5 items per Iteration

c#linq

提问by Kasrak

Linq Select 5 items each time based on our enumerator

Linq 根据我们的枚举器每次选择 5 个项目

Our List e.g "theList"has 100 items, Want to go through the list and Select 5 items in each iterations,

我们的列表例如"theList"100 个项目,想要遍历列表并在每次迭代中选择 5 个项目

Sample Code, which we want to change this into our desired result :

示例代码,我们希望将其更改为我们想要的结果:

        theList = dt.AsEnumerable()
            .Select(row => new CustItem
            {
                Name = row.Field<string>("tName"),
                Title = row.Field<string>("tTitle"),
            }).ToList();

We should Iterate it within a loop and process on the selected 5 items each time, or pass it to our other methods :

我们应该在循环中迭代它并每次处理选定的 5 个项目,或者将其传递给我们的其他方法:

something like it :

类似的东西:

for (int i=0; i < 20 ; i++)

I want to use "i"enumerator on the linq selectstatement and make a multiplicity to make the boundaries of our new resultset.

我想"i"linq select语句上使用enumerator并进行多重性来确定我们新结果集的边界。

采纳答案by Govind Malviya

for (int i=0; i < 20 ; i++)
{
    var fiveitems = theList.Skip(i*5).Take(5);
}

回答by Jon Skeet

It sounds like you want the Batchoperator from MoreLINQ:

听起来您想要Batch来自MoreLINQ的运算符:

foreach (var batch in query.Batch(5))
{
    foreach (var item in batch)
    {
        ...
    } 
}

回答by Simon M?Kenzie

You can also do this with pure linq by taking advantage of integer arithmetic and the GroupBymethod:

您还可以通过利用整数运算和GroupBy方法使用纯 linq 执行此操作:

int blockSize = 5;
var group = theList.Select((x, index) => new { x, index })
                   .GroupBy(x => x.index / blockSize, y => y.x);

foreach (var block in group)
{
    // "block" will be an instance of IEnumerable<T>
    ...
}

There are a number of advantages to this approach which aren't necessarily immediately apparent:

这种方法有许多优点,但不一定立即显现:

  • Execution is deferred, so it's efficient when you're working with conditional processing
  • You don't need to know the length of the collection, thus avoiding multiple enumeration while also being generally cleaner than other approaches
  • 执行被推迟,所以当你使用条件处理时它是高效的
  • 您不需要知道集合的长度,从而避免了多次枚举,同时通常也比其他方法更干净

回答by Jamie Pearcey

The following static extension method would make it a straightforward process to break up a list into multiple lists of a specific batch size.

以下静态扩展方法将使将列表分解为特定批量大小的多个列表变得简单。

    public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> items, int noOfItemsPerBatch)
    {
        decimal iterations = items.Count() / noOfItemsPerBatch;

        var roundedIterations = (int)Math.Ceiling(iterations);

        var batches = new List<IEnumerable<T>>();

        for (int i = 0; i < roundedIterations; i++)
        {
            var newBatch = items.Skip(i * noOfItemsPerBatch).Take(noOfItemsPerBatch).ToArray();
            batches.Add(newBatch);
        }

        return batches;
    }

Example of use

使用示例

var items = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var batchedItems = items.Batch(4);

Assert.AreEqual(batchedItems.Count() == 3);
Assert.AreEqual(batchedItems[0].Count() == 4);
Assert.AreEqual(batchedItems[1].Count() == 4);
Assert.AreEqual(batchedItems[2].Count() == 2);

回答by Nalan Madheswaran

Try this one:

试试这个:

 for (int i = 0; i < list.Count; i = i + 5) {
                var fiveitems = list.Skip(i).Take(5);
                foreach(var item in fiveitems)
                {

                }
            }