你如何 JOIN/GROUP/Max/Min 都在 Linq 中?

How do you JOIN/GROUP/Max/Min all within Linq?

我有以下 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 面部列外,它可以满足我的所有需求。我不确定该怎么做,因为我正在 joining 一个 table 但需要从另一个 table.

聚合数据

任何人都可以帮助我将此查询作为 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)
    };