使用Linq处理列表中的项目组 [英] use Linq to process groups of items in a list

查看:76
本文介绍了使用Linq处理列表中的项目组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
将LINQ分区列表分为8个成员的列表
如何对可枚举对象进行分块?

Possible Duplicate:
LINQ Partition List into Lists of 8 members
how do I chunk an enumerable?

我有很多项目的列表,并且有一个方法可以在这些项目的较短列表上很好地工作.

I have a list of many items, and a Method that works well on shorter lists of those same items.

我可以使用LINQ从大列表中提取N个元素,然后一次将它们传递到Method中吗?我敢肯定有一种优雅的方法可以解决这个问题,而不必设置"int i = 0;".变量.

Can I use LINQ to pull off N elements from the big list, and pass them into the Method, N at a time? I'm sure there is an elegant way to to this without having to make an "int i=0;" variable.

让我清楚一点,我知道foo.Take(10)将使我从清单中删除10个项目.但是我需要继续处理下一组10,然后处理下一组10,依此类推.伪代码应类似于:

Let me be clear, I know that foo.Take(10) will get me 10 items off the list. But I need to keep processing the next set of 10, then the next set of 10 and so on. The pseudo code should be something like:

var shortList = BigList.NiceMethod(10);
foreach (shorty in shortlist)
{
  Method(shorty);
}

这可能是一些群组通话.

This is probably some Group call.

推荐答案

这将为您提供一个列表列表,其中每个列表最多包含N个元素.

This will give you a list of Lists where every List has at most N elements.

int N = 3;
List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var ListOfLists = list.Select((x, inx) => new { Item = x, Group = inx / N })
                        .GroupBy(g => g.Group, g => g.Item)
                        .Select(x => x.ToList())
                        .ToList();

您还可以使用Morelinq的批处理方法

You can also use Morelinq's Batch method

var ListOfLists2 = list.Batch(3).Select(x => x.ToList()).ToList();

这篇关于使用Linq处理列表中的项目组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆