gpt4 book ai didi

c# - Linq 聚合对象和列表

转载 作者:太空宇宙 更新时间:2023-11-03 11:35:07 24 4
gpt4 key购买 nike

我用 NHibernate 做这个查询:

    var test = _session.CreateCriteria(typeof(Estimation))
.SetFetchMode("EstimationItems", FetchMode.Eager)
.List();

一个“估计”可以有多个“估计项目”(数量、价格和 ProductId)

我想要一个具有这些约束的“估计”列表:

  1. 图片上的“估计”代码一行(例如:2011/0001 和 2011/0003)
  2. 通过估计(每行的平均值)“EstimationItems”的数量
  3. 通过估算(每行的意思)每个“EstimationItems”的总价(数量 * 价格)

希望下图结构更清晰

谢谢,

enter image description here

enter image description here

最佳答案

这里有一个建议:

var stats =
from estimation in test
group estimation by estimation.code into gestimation
let allItems = gestimation.SelectMany(x => x.EstimationItems)
select new
{
Code = gestimation.Key,
ItemNumber = allItems.Count(),
TotalPrice = allItems.Sum(item => item.Price * item.Quantity)
};

现在这将创建一个匿名类型,它具有您想要的三个属性(估算代码、此估算代码的项目数量以及此估算代码的项目总价)。

您可以根据特定需求对其进行调整。请记住 allItems 是一个 IEnumerable<EtimationItem>包含属于具有相同代码的 Estimation 的所有 EstimationItem。

如果你想在创建它的方法的范围之外使用这个对象,你不能用匿名类型来做,那么你应该创建一个类来保存这些值。

更正命题:命题:

var stats =
(from est in test.Cast<Estimation>()
group est by est.code into gEst
let allItems = gEst.SelectMany(est => est.EstimationItems).Cast<EstimationItem>()
select new TestingUI
{
Code = gEst.Key,
Quantity = gEst.Count(),
Total = gEst.Sum(item => item.Price * item.Quantity)
}).ToList();

关于c# - Linq 聚合对象和列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6519879/

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