简体   繁体   English

C#实体框架-如何返回具有最大值的列表?

[英]C# Entity Framework - How to return a list with Max value?

To start, I have a database modeled using the Entity Framework with the following structure: 首先,我有一个使用实体框架建模的数据库,其结构如下:

Pedidos :
--------
IDPedidoDetalhe (int, not null)
IDPedido  (int, not null)
Aditamento (int, not null)
Semana  (int, null)
Ano  (int, null)
Titulo  (nvarchar(250), null)

I'm trying to create a query that finds the line of the table with the "IDPedido" required and the max value for "Aditamento". 我正在尝试创建一个查询,以查找所需的“ IDPedido”和“ Aditamento”最大值的表格行。 To find the max value for a required item (npedido), i use: 为了找到所需项目(npedido)的最大值,我使用:

List<Pedidos> lista = db.Pedidos.Where(m => m.IDPedido == npedido).ToList();
var pedido = lista.Select(m => m.Aditamento).Max(x => x);

But I want the line in the list (all the columns) and no just the value for "Aditamento". 但是我想要列表中的行(所有列),而不仅仅是“ Aditamento”的值。

Can you help me, with this query? 这个查询可以帮我吗?

You are loosing all fields of Pedido entity when you are doing projection to Aditamento with Select(m => m.Aditamento) . 使用Select(m => m.Aditamento)投影到Aditamento时,您失去了Pedido实体的所有字段。 For getting single Pedido by id, with max Aditamento value you should simply order filtered Pedidos by Aditamento and select first one: 要通过ID获取单个Pedido,并获得最大Aditamento值,您只需订购Aditamento过滤的Pedidos,然后选择第一个:

var pedido = db.Pedidos.Where(p => p.IDPedido == npedido)
               .OrderByDescending(p => p.Aditamento)
               .FirstOrDefault();

For getting all Pedidos with max Aditamento value you need to group filtered Pedidos by Aditamento and select group with max key value: 要获取所有具有最大Aditamento值的Pedido,您需要按Aditamento对过滤的Pedidos进行分组,然后选择具有最大键值的组:

var pedidos = db.Pedidos.Where(p => p.IDPedido == npedido)
                .GroupBy(p => p.Aditamento)
                .OrderByDescending(g => g.Key)
                .FirstOrDefault();

If you want list, then check if you have found any pedidos by id and convert group to list: 如果要列出,请检查是否已通过ID找到任何pedido,并将组转换为列表:

if (pedidos != null)
{
    List<Pedido> result = pedidos.ToList();
}

This should do: 应该这样做:

List<Pedidos> lista = db.Pedidos.Where(m => m.IDPedido == npedido).ToList();

var maxValue= lista.Max(x => x.Aditamento);

// IEnumerable with all lines that have the "maxValue"
var lineWithMaxValue = lista.Where(x => x.Aditamento == maxValue); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM