简体   繁体   中英

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". To find the max value for a required item (npedido), i use:

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".

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) . For getting single Pedido by id, with max Aditamento value you should simply order filtered Pedidos by Aditamento and select first one:

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:

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:

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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