LINQ 查询按某些条件将有序列表拆分为连续点的子列表
寻求针对某些对象编写 LINQ 查询的帮助。我觉得如果我的 LINQ 技能更像忍者,我可以使用一些聪明的 GroupBy/SelectMany (或其他东西?!) 来做到这一点。
一般而言,问题是:给定按某种顺序排列的对象列表,其中每个对象都有一个标志,如何将列表拆分为子列表,其中每个子列表是设置标志的所有连续点?
执行此操作的命令式方法类似于以下伪代码:
foreach object obj
if(obj.FlagSet)
add it to my currentsublist
else
skip to the next obj where FlagSet and start a new sublist
因此,给定以下输入:
{ 1, Flag }, { 2, Flag }, {3, NoFlag }, {4, Flag}, {5, NoFlag}, {6, Flag}...
我想要以下输出:
列表 1:{1, 2} 列表 2:{4} 列表 3:{6}
我想通过 LINQ 来实现它的功能。有什么想法吗?
(我首先环顾四周,但我看到的所有问题似乎都想简单地对列表进行分组或分成相等的大小,这对我没有帮助。)
Looking for help writing a LINQ query on some objects. I feel if my LINQ skills were more ninja I could do this with some clever GroupBy/SelectMany (or something?!).
Stated generically, the question is: given a list of objects in some sort of order, where each object has a Flag, how do I split the list into sub-lists, where each sublist is all of the contiguous points where the flag is set?
An imperative way of doing this would be like the following pseudocode:
foreach object obj
if(obj.FlagSet)
add it to my currentsublist
else
skip to the next obj where FlagSet and start a new sublist
So, given the following input:
{ 1, Flag }, { 2, Flag }, {3, NoFlag }, {4, Flag}, {5, NoFlag}, {6, Flag}...
I'd like the following output:
List 1: {1, 2}
List 2: {4}
List 3: {6}
And I'd like to do it functionally via LINQ. Any ideas?
(I have looked around first, but all the questions I could see appeared to want to either simply group a list or to split into equal sizes, which hasn't been helpful for me.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
此 MSDN 文章提供了按连续值进行分组的代码:
http://msdn.microsoft。 com/en-us/library/cc138361.aspx
我已经从上面的链接复制了代码,以防链接腐烂:
它不漂亮,但效果很好。
在你的情况下,它会是这样的:
This MSDN article provides code to group by contiguous values:
http://msdn.microsoft.com/en-us/library/cc138361.aspx
I've reproduced the code from the link above in case of link-rot:
It's not pretty, but works well.
In your case it would be something like:
除了 @spenders 优秀链接(+1!) 之外,我还要补充一点
:漂亮,而且运行良好:
IGrouping
的Chunk
集成到标准 linq我现在看到的唯一真正抱怨是它无法主动处理从源获取的枚举器可数。这是我的相关修复:
更新
这是我完全修改的源代码,修复了上面列出的所有问题。 **这也使得
Chunk
成为一次性的:In addition to @spenders excellent link (+1!), I'd add:
It is pretty, and it works well:
Chunk<>
which implementsIGrouping<>
The only real gripe I saw right now was that it fails to pro-actively dispose the enumerators it gets from the source enumerable. Here is my relevant fix:
Update
Here is my completely amended source, fixes all the issues listed above. **This also makes
Chunk<>
disposable:我认为你管理两个列表的方法是
过去只需将第一个列表添加到最终列表并清除第一个列表
并在设置标志时将对象添加到第一个列表
I think the way is you manage two list
and on else past just add first list to final list and clear first list
and add object to first list when flag is set
通过 LINQ
By LINQ