将列表拆分为列表列表,按元素拆分
可以重写以下内容,以便使用 LINQ(而不是这些老式的 foreach
循环),
IEnumerable<IEnumerable<T>> SplitIntoSections<T>(IEnumerable<T> content,
Func<T, bool> isSectionDivider)
{
var sections = new List<List<T>>();
sections.Add(new List<T>());
foreach (var element in content)
{
if (isSectionDivider(element))
{
sections.Add(new List<T>());
}
else
{
sections.Last().Add(element);
}
}
return sections;
}
当我意识到它时,我以为我几乎有办法做到这一点(它涉及 FSharp 集合)可以通过 foreach 循环来完成。
Can the following be rewritten so that is uses LINQ, (rather an these old-fashioned foreach
loops)
IEnumerable<IEnumerable<T>> SplitIntoSections<T>(IEnumerable<T> content,
Func<T, bool> isSectionDivider)
{
var sections = new List<List<T>>();
sections.Add(new List<T>());
foreach (var element in content)
{
if (isSectionDivider(element))
{
sections.Add(new List<T>());
}
else
{
sections.Last().Add(element);
}
}
return sections;
}
I thought I almost had an way of doing this, (it involved FSharp colections) when i realised that it could be done with a foreach
loop.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不想在这里使用 LINQ。如果不做一些粗俗的事情,你将无法以正确的方式进行排序和分组。
最简单的方法是使用
产量
声明。一个简单的方法如下:这里有一个问题;对于非常大的组,将子组存储在列表中效率很低,它们也应该被流出来。您的方法的问题在于您有一个需要在每个项目上调用的函数;它会干扰流操作,因为一旦找到分组就无法向后重置流(因为您实际上需要两个方法来产生结果)。
You don't want to use LINQ here. You aren't going to be able to order and group the proper way without doing something gnarly.
The easy thing to do is to take your code and make it defer execution using the
yield
statement. An easy way to do this is as follows:There's a problem here; for very large groups, it's inefficient to store the sub-groups in a list, they should be streamed out as well. The problem with your approach is that you have a function that is required to be called on each item; it interferes with the stream operation since one can't reset the stream backwards once the grouping is found (as you effectively need two methods that yield results).
这是一个低效但纯粹的 LINQ 解决方案:
Here's an inefficient but pure LINQ solution:
您可以使用仅在明确定义的区域内使用的副作用...它很臭,但是:
必须有一个更好的替代方案...如果需要,
Aggregate
会带您到达那里......但总的来说我同意casperOne,这种情况最好在 LINQ 之外处理。
You could use a side-effect which is only used within a well-defined area... it's pretty smelly, but:
There must be a better alternative though...
Aggregate
will get you there if necessary...... but overall I agree with casperOne, this is a situation best handled outside LINQ.
好吧,我在这里使用一种 LINQ 方法,尽管它并不特别符合您的问题的精神,但我认为:
我相信您会注意到完全缺乏错误检查,如果您决定使用此代码...
Well, I use one LINQ method here, though it's not particularly in the spirit of your question, I think:
I trust you will note the complete lack of error checking, should you decide to use this code...