是否可以重写以下内容以便使用 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;
}
当我意识到它可以通过 foreach
循环完成时,我以为我几乎有办法做到这一点(它涉及 FSharp 集合)。
最佳答案
您不想在这里使用 LINQ。如果不做一些粗糙的事情,您将无法以正确的方式进行排序和分组。
最简单的做法是获取您的代码并使用 yield
statement 使其延迟执行。 .一个简单的方法如下:
IEnumerable<IEnumerable<T>> SplitIntoSections<T>(this IEnumerable<T> source,
Func<T, bool> sectionDivider)
{
// The items in the current group.
IList<T> currentGroup = new List<T>();
// Cycle through the items.
foreach (T item in source)
{
// Check to see if it is a section divider, if
// it is, then return the previous section.
// Also, only return if there are items.
if (sectionDivider(item) && currentGroup.Count > 0)
{
// Return the list.
yield return currentGroup;
// Reset the list.
currentGroup = new List<T>();
}
// Add the item to the list.
currentGroup.Add(item);
}
// If there are items in the list, yield it.
if (currentGroup.Count > 0) yield return currentGroup;
}
这里有问题;对于非常大的组,将子组存储在列表中效率低下,它们也应该流出。您的方法的问题在于您有一个需要在每个项目上调用的函数;它会干扰流操作,因为一旦找到分组就无法向后重置流(因为您实际上需要两种方法来产生结果)。
关于c# - 将列表拆分为列表列表,拆分元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7636346/