gpt4 book ai didi

c# - LINQ - 聚合和计算多个参数

转载 作者:太空狗 更新时间:2023-10-30 00:52:42 24 4
gpt4 key购买 nike

我有以下内容

List<Stock> _investments= new List<Stock>()
{
new Stock {id=msft, price =12, qty=20}
new Stock {id=msft, price =53, qty=50}
new Stock {id=csco, price =222, qty=20}
new Stock {id=fb, price 40, qty=100}
}

给定一个符号,比如 msft,我想获得总投资和收取的价格。在上述情况下,它将是

id=msft, qty=70, price = (12*20 + 53 *50)/70 = 41.29

如何在 LINQ 中做到这一点?我可以这样得到 12*20 + 53*50:

var c = _investments.Where(i => i.ID == investmentName.ToUpper()).Sum(k => k.InitialPrice * k.Qty);

但是如何以一种有效的方式包含总数量

最佳答案

最简单的方法似乎是:

var relevantInvestments = _investments
.Where(i => i.ID == investmentName.ToUpper())
.ToArray();

var totalQty = relevantInvestments.Sum(k => k.Qty);
var c = relevantInvestments.Sum(k => k.InitialPrice * k.Qty) / totalQty;

只迭代一次:

var c = _investments
.Where(i => i.ID == investmentName.ToUpper())
.Aggregate(
new { Price = 0, TotalQty = 0 },
(total, i) => new
{
Price = total.Price + i.InitialPrice * i.Qty,
TotalQty = total.TotalQty + i.Qty
},
i => i.Price / i.TotalQty);

关于c# - LINQ - 聚合和计算多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20316912/

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