LINQ查询拆分的有序列表到一些标准的连续点的子列表 [英] LINQ query to split an ordered list into sublists of contiguous points by some criteria
问题描述
寻找帮助,写上一些对象LINQ查询。我觉得如果我的LINQ的技能更忍者,我可以用一些巧妙的GROUPBY /的SelectMany(或某事?!)做到这一点。
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
因此,考虑下列输入:
{1,旗},{2,标志},{3,NoFlag},{4,标志},{5,NoFlag},{6}旗...
{ 1, Flag }, { 2, Flag }, {3, NoFlag }, {4, Flag}, {5, NoFlag}, {6, Flag}...
想我下面的输出:
表1:{1,2}
清单2:{4}
清单3:{6}
List 1: {1, 2} List 2: {4} List 3: {6}
和我想通过LINQ做功能。任何想法?
And I'd like to do it functionally via LINQ. Any ideas?
(我先环顾四周,但所有的问题,我可以看到似乎想要么干脆组列表或分割成大小相等,这不是招。'T很有帮助对我来说)
(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.)
推荐答案
这MSDN文章连续值提供了代码组:
This MSDN article provides code to group by contiguous values:
http://msdn.microsoft.com/en-us/library /cc138361.aspx
这不是很漂亮,但效果很好。
It's not pretty, but works well.
在你的情况下,会是这样的:
In your case it would be something like:
myList.ChunkBy( o => o.FlagSet )
这篇关于LINQ查询拆分的有序列表到一些标准的连续点的子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!