c# - 将列表拆分为列表列表,拆分元素

标签 c# linq aggregate

是否可以重写以下内容以便使用 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/

相关文章:

Oracle SELECT 查询 : collapsing null values when pairing up dates

c# - LINQ 按嵌套在 3 个列表中的属性筛选

sql - 唯一标识符 (GUID) 上的聚合函数

elasticsearch - 汇总中位数/平均值查询

c# - Azure Functions : how do you read the settings in host. json 在运行时?

c# - 将 LINQ 的输出转换为 Int16

c# - Linq 从属性符合条件的列表中选择

c# - 将 ASP.NET MVC 模型封装为可重用程序集

c# - WebAPI OData 预过滤扩展查询

c# - 如何在 lucene 搜索中添加特殊字符? C#