gpt4 book ai didi

c# - 使用 List.ToLookup()

转载 作者:太空狗 更新时间:2023-10-29 20:49:17 25 4
gpt4 key购买 nike

我有一个如下所示的列表:

var products = new List<Product>
{
new Product { Id = 1, Category = "Electronics", Value = 15.0 },
new Product { Id = 2, Category = "Groceries", Value = 40.0 },
new Product { Id = 3, Category = "Garden", Value = 210.3 },
new Product { Id = 4, Category = "Pets", Value = 2.1 },
new Product { Id = 5, Category = "Electronics", Value = 19.95 },
new Product { Id = 6, Category = "Pets", Value = 5.50 },
new Product { Id = 7, Category = "Electronics", Value = 250.0 },
};

我想按类别分组并获取属于该类别的“值”的总和..示例:电子产品:284.95

虽然我可以通过其他方式做到这一点,但我想学习 Look-Up 的用法。

是否有可能在查找中获得这 2 个值(类别和值)?如果是,我该怎么做?

最佳答案

当您从 Lookup 中按键检索时,它的行为就像一个分组,因此您可以这样做:

var productLookup = products.ToLookup(p => p.Category);
var electronicsTotalValue = productLookup["Electronics"].Sum(p => p.Value);
var petsTotalValue = productLookup["Pets"].Sum(p => p.Value);
//etc

var totalValue = products.Sum(p => p.Value);
// I wouldn't use the Lookup here, the line above makes more sense and would execute faster
var alsoTotalValue = productLookup.Sum(grp => grp.Sum(p => p.Value));

关于c# - 使用 List.ToLookup(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16075092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com