如何使用 Enumerable.Aggregate 而不出现 CS0411 错误

问题描述 投票:0回答:1

有两条DTO记录:

public record struct DateHour(int Hour, double? Value);
private record struct HourSnapshot(uint TotalSeconds, double? Value);

我有另一种与枚举一起使用的方法。为了简洁起见,我只是提供了 switch 表达式的手:

HistoryType.LastValueChange => GetTagHourHistory(tagID, scannerName!, dateTime, true)
          .OrderBy(hs => hs.TotalSeconds).Aggregate(null,
            (lastChange, current) => (lastChange is HourSnapshot hs && hs.Value != current.Value) 
              ? lastChange with { TotalSeconds = current.TotalSeconds, Value = current.Value }
              : current,
            aggrResult => (aggrResult is not null)
              ? new DateTime(dateTime.Year, dateTime.Month, dateTime.Day) + TimeSpan.FromSeconds(hs.TotalSeconds)
              : null),

它的作用是从 GetTagHourHistory 方法中查找 IEnumerable 并尝试查找数据源中标签的最后一个值更改。

我收到一个编译器错误,提示“尝试显式定义参数类型”。一旦我将调用更改为

Aggregate<DateHour?>
,它就会失败并显示错误“没有重载有三个参数”。

根据 MSDN,

resultSelector
谓词存在重载:

public static TResult Aggregate<TSource,TAccumulate,TResult> (this System.Collections.Generic.IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate,TSource,TAccumulate> func, Func<TAccumulate,TResult> resultSelector);

它怀疑我的聚合的种子值为空,但根据 MSDN 的说法,唯一要做的事情是,使用显式类型表示法是错误的。

c# linq .net-6.0 aggregate-functions
1个回答
0
投票

首先可以确保lastChange可以为null,使用HourSnapshot?作为种子类型。然后还要确保它可以与 HourSnapshot 一起使用吗?和 HourSnapshot ,它返回正确的类型,即 DateTime?。

您可以使用类似的东西来存档预期的输出。

此代码尚未经过测试,

HistoryType.LastValueChange => GetTagHourHistory(tagID, scannerName!, dateTime, true)
    .OrderBy(hs => hs.TotalSeconds)
    .Aggregate<HourSnapshot?, HourSnapshot?, DateTime?>(
        null,
        (lastChange, current) => (lastChange is HourSnapshot hs && hs.Value != current.Value)
            ? lastChange with { TotalSeconds = current.TotalSeconds, Value = current.Value }
            : current,
        aggrResult => (aggrResult is HourSnapshot hs)
            ? new DateTime(dateTime.Year, dateTime.Month, dateTime.Day) + TimeSpan.FromSeconds(hs.TotalSeconds)
            : null
    ),
© www.soinside.com 2019 - 2024. All rights reserved.