linq query on 2 group by lists

1

I have the following query in linq, which takes 2 lists as a data source. The first contains a list of IdProducto and its description

public class Productos
{
    public List<Producto> lstProductos { get; set; }
}
public class Producto
{
    public string id { get; set; }
    public string name { get; set; }
}

and the other list has the products sold

public class Venta
{
    public string ProductoId { get; set; }
    public string clienteRut { get; set; }
}

public class Ventas
{
    public List<Venta> lstVentas { get; set; }
}

I need to consult the 5 most sold products, ordered by quantity from the most sold, to the least sold.

So far I have the following linq query, but I do not know how to do it so that it gives me the list of the first 5, ordered from highest to lowest based on the count

      Venta vta1 = new Venta();
        vta1.ProductoId = "1";
        vta1.clienteRut = "121370654";

        Venta vta2 = new Venta();
        vta2.ProductoId = "2";
        vta2.clienteRut = "121370654";

        Venta vta3 = new Venta();
        vta3.ProductoId = "3";
        vta3.clienteRut = "121370654";


        List<Venta> lstVentasDia = new List<Venta>();
        lstVentasDia.Add(vta1);
        lstVentasDia.Add(vta2);
        lstVentasDia.Add(vta3);

        VentasDia vtas = new VentasDia();
        vtas.date = "2018-05-01";
        vtas.lstVentas = lstVentasDia;


        var Lista5Top = from vendidos in vtas.lstVentas
                        orderby vendidos.ProductoId
                        group vendidos by vendidos.ProductoId into Grupo
                        select new { key = Grupo.Key, cont = Grupo.Count()};

I need that group of results, add the name of the product that is in the list Products, and order it by quantity sold from highest to lowest and get the 5 products with the largest amount.

Thankful in advance Glory

    
asked by Gloria 24.06.2018 в 22:47
source

1 answer

0

so I see you have to sort the result list and select the first 5. This would look like this:

var Lista5Top = (from vendidos in vtas.lstVentas
                orderby vendidos.ProductoId
                group vendidos by vendidos.ProductoId into Grupo
                select new { key = Grupo.Key, cont = Grupo.Count()}).OrderByDescending(v => v.cont).Take(5);

Greetings

    
answered by 25.06.2018 / 08:24
source