Help with a query in linq

4

I want to make a classification so to speak of a list that I have, I'm trying to do it with linq. well this is what I want ..

Result. This the information with which I count.

Proveedor: Videmont
Cap. Morgan = $450.12
ET. Negra   = $620.32
Proveedor: HEB
Cap. Morgan = $400.50
ET. Negra   = $508.79
Proveedor: Alamo
Cap. Morgan = $300.48
ET. Negra   = $589.46

I want to take the Cap products. Morgan and ET. Negra, whose price is the lowest, of the suppliers. and the result is this, seeing it so simple.

Alamo: Morgan    = $300.48
HEB:   ET. Negra = $508.79

This is the code with which you already classify the data.

  var prove2 = compra.GroupBy(x => x.Proveedor).Select(g => new
                {
                    Proveedor = g.FirstOrDefault().Proveedor,
                    Productos = g.Select(y => new {
                        Producto = y.Producto,
                        PrecioMenor = y.MenorPrecio
                    }),
                    CantidadCotizada = g.FirstOrDefault().CantidadCotizada,
                    MenosPrecio = g.Select(r => r.MenorPrecio).Min(),

                }).ToList();

The result is drawn in this scheme.

Proveedor 
|__ Productos
            |_Producto1
                      |_ Producto
                      |_ MenorPrecio

Videmont
|__ Cap. Morgan
|__ $450.12
|__ ET. Negra 
|__ $620.32

I would like to take the products with the lowest price of each bone of Morgan and Et. Negra, with its respective provider. I hope someone guides me. thanks

    
asked by JuanL 27.06.2018 в 01:42
source

1 answer

3

Since I do not know exactly what your data model is, I can not give you an exact solution. But let's see if this helps you.

Instead of grouping by Proovedor, as you are interested in the cheapest prices per product, what you should do is group by product. Then, you simply get the minimum price per product.

The most complex thing is to obtain the supplier of that cheaper product. There are several ways to do it, but a very simple one is to simply look for the record whose price matches the lowest.

In short, it would be something like this:

var masbaratos = compra.GroupBy(x => x.Producto).Select(g => new
{
    Producto = g.Key,
    PrecioMenor = g.Min(x => x.MenorPrecio),
    Proveedor = g.Where(x => x.MenorPrecio == g.Min(y => y.MenorPrecio) && x.Producto==g.Key).First().Proveedor
}).ToList();
    
answered by 27.06.2018 / 15:58
source