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

标签 c# linq linq-to-sql

我有以下 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/

相关文章:

c# - 一些 Python 函数的 .NET 等价物

c# - WinForm 事件处理程序激活速度太慢

c# - USPS 地址验证 API : If & or # symbol in address field then API returns error response

c# - 如何解析包含节点列表的 XML 文件?

linq-to-sql - 是否有一个简单的实现来在通用 F# 查询中使用谓词函数

C#在Dictionary中添加字典

c# - 将列表中的值与另一个列表中的特定总和进行比较的最快方法是什么?

c# - 使用 linq foreach 更新 2 个字段

c# - from 关键字是否比 C# 中的直接方法调用更可取?

linq-to-sql - 直接使用 LINQ 生成的类?