C#是否有一个等同于F#的Seq.scan的LINQ--像fold一样,但在每一步都存储聚合值?(像reduce这样不需要启动状态的LINQ至少也可以).

如果不存在,我可以通过编写自己的或使用LanguageExt的方法来解决它的缺失,但我更喜欢在可能的情况下使用核心库.

推荐答案

C#没有与F#的Seq.scan方法等价的直接LINQ.

您可以使用LINQ聚合器方法模拟此功能,方法是将集合作为种子值传递并对前面的累加执行查找:

public class Data
{
    public int Count { get; set; }
}

var data = new List<Data> 
{ 
    new Data { Count = 1 }, 
    new Data { Count = 2 }, 
    new Data { Count = 1 }, 
    new Data { Count = 5 }, 
    new Data { Count = 3 } 
};

var accumulatedValues = data.Aggregate(new List<int>(), (current, nextValue) =>
{
    var lastValue = current.Count > 0 ? current[current.Count - 1] : 0;
    var updatedValue = lastValue + nextValue.Count;
    current.Add(updatedValue);
    return current;
});

此外,创建自己的扩展方法模仿Aggregate函数,但返回所有累加步骤的列表,而不是返回单个值,这是相对简单的.

public static class Extensions
{
    public static IEnumerable<TAccumulate> Accumulate<TSource, TAccumulate>(
        this IEnumerable<TSource> source, 
        TAccumulate seed, 
        Func<TAccumulate, TSource, TAccumulate> accumulat或)
    {
        var accumulation = new List<TAccumulate>();

        var current = seed;
        f或each (var item in source)
        {
            current = accumulat或(current, item);
            accumulation.Add(current);
        }

        return accumulation;
    }
}

这对原始值集合和对象集合都很有效:

var firstAccumulation = 
    Enumerable.Range(1, 10).Accumulate(0, (acc, newValue) => acc + newValue);

public class Data
{
    public int Count { get; set; }
}

var data = new List<Data> 
{ 
    new Data { Count = 1 }, 
    new Data { Count = 2 }, 
    new Data { Count = 1 }, 
    new Data { Count = 5 }, 
    new Data { Count = 3 } 
};

var secondAccumulation = data.Accumulate(0, (acc, newValue) => acc + newValue.Count);

Csharp相关问答推荐

如何使用FastEndpoints和.NET 8 WebAppliationBuilder进行集成测试?

在ASP.NET中为数据注释 Select 合适的语言

为什么使用DXGI输出复制和Direct 3D时捕获的图像数据全为零?

错误NU 1301:无法加载源的服务索引

Monty Hall游戏节目模拟给我50/50的结果

使用LayoutKind在C#中嵌套 struct .显式

如何将ASP.NET Core 2.1(在.NET框架上运行)更新到较新的版本?

如何使用XmlSerializer序列化带有CDATA节的XML文件?

用于管理System.Text.Json中的多态反序列化的自定义TypeInfoResolver

如何比较C#中的L和ł(波兰字符)返回TRUE

当我没有此令牌时,为什么语法报告EOF错误?

Selify只更改第一个下拉菜单,然后忽略REST-C#

Regex字母数字校验

如何在不复制或使用输出的情况下定义项目依赖

.NET8->;并发词典总是比普通词典快...怎么回事?[包含基准结果和代码]

在平行内使用跨度.用于循环

工厂类是如何在.NET 8中注册的?

仅在Blazor Web App中覆盖生产的基本路径(.NET8中的_Hosts.cshtml文件功能?)

.NET EF Core Automapper项目到筛选不起作用

从列表中跳过和获取条目的优雅方式