C# 字典在使用 ulong 时不包含 sum 的定义

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

我有一个

Dictionary<string, DemoRecord>
,其中
DemoRecord
有一个字段
Size
。 我现在想使用 LINQ 计算所有大小的总和。这是例子

public record DemoRecord(string Name, ulong Size);

public class DemoStackOverflow()
{
    public ulong GetSum(Dictionary<string, DemoRecord> data)
    {
        return data.Sum(x => x.Value.Size); // Syntax error
    }
}

但是,Visual Studio 突出显示了

Sum
方法,并带有错误消息,我无法理解该问题。

enter image description here

当显式指定泛型类型时,它只会突出显示

data
变量并显示另一条错误消息。

enter image description here

这不可能吗?这看起来确实是一个微不足道的 LINQ 方法。 Visual Studio 本身表明

Sum
存在于
Dictionary
上。为什么罪魁祸首是
ulong

enter image description here

编辑 这段代码在使用

int
时没有问题 enter image description here

c# linq
1个回答
0
投票

你需要像这样总结字典中的值。

long totalSize = myDictionary.Values.Sum(record => (long)record.Size);

Sum 也不支持 ulong,所以这就是为什么你还需要转换为 long。

© www.soinside.com 2019 - 2024. All rights reserved.