gpt4 book ai didi

c# - 你如何在 Linq 中加入/组/最大/最小?

转载 作者:太空宇宙 更新时间:2023-11-03 19:54:54 26 4
gpt4 key购买 nike

我有以下 SQL 语句:

select 
p.productId,
p.minAge,
p.maxAge,
min(pcb.lowerbound) MinValue,
max(pcb.upperBound) MaxValue,
p.name ProductName
from gliweb..product p
inner join gliweb..ProductClassBand pcb on pcb.productId = p.productId
where p.IncludeInQuote = 1
and @currentAge between p.minAge and p.maxAge
group by p.productId, p.minAge, p.maxAge, p.name
order by p.name

如您所见,这是一个简单的语句,先是 GROUP,然后是 MIN/MAX。我正在尝试将此查询转换为 C# LINQ,但遇到了困难。

到目前为止,我有以下内容:

var productListDatabase = from products in DataContext.Products
join band in DataContext.ProductClassBands on products.productId equals band.productId
where products.minAge <= currentAge &&
products.maxAge >= currentAge &&
products.IncludeInQuote == true
orderby products.name
group products by new{
products.productId,
products.minAge ,
products.maxAge,
products.name
} into g

select new
{
g.Key.maxAge,
g.Key.minAge,
g.Key.productId,
g.Key.name
//,minFace = (from t2 in band select t2.
};

除了 MIN/MAX 面列外,它可以完成我需要的一切。我不确定如何执行此操作,因为我正在加入一个表但需要从另一个表聚合数据。

谁能帮我用 Linq 语句完成这个查询?

最佳答案

首先,您需要使用 group join

Group Join

A join clause with an into expression is called a group join.

A group join produces a hierarchical result sequence, which associates elements in the left source sequence with one or more matching elements in the right side source sequence. A group join has no equivalent in relational terms; it is essentially a sequence of object arrays.

这里是查询

var productListDatabase = from product in DataContext.Products
join band in DataContext.ProductClassBands on product.productId equals band.productId into productBands
where product.minAge <= currentAge &&
product.maxAge >= currentAge &&
product.IncludeInQuote == true
group new { product, productBands } by new {
product.productId,
product.minAge ,
product.maxAge,
product.name
} into g
orderby g.Key.name
select new
{
g.Key.maxAge,
g.Key.minAge,
g.Key.productId,
g.Key.name,
minFace = g.SelectMany(e => e.productBands).Min(band => band.lowerbound),
maxFace = g.SelectMany(e => e.productBands).Max(band => band.upperBound)
};

关于c# - 你如何在 Linq 中加入/组/最大/最小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34775520/

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