How to make this FOR (in C #) list only the top five items?

0

I have an ordered list, that I need to display only the first 5 items, not all the bank records, so I'm not getting it. Here is my code as it is:

public class DashboardController : Controller
    {
        private NFeWebContext db = new NFeWebContext();
        // GET: Dashboard
        public ActionResult Index()
        {
            var dashboard = new DashboardViewModel();
            var lista = new List<NotaFiscal>();
            var participantes = db.Participantes
                              .ToList();
            var notas = db.NotasFiscais
                          .ToList();

            foreach (var part in participantes)
            {
                var x = new NotaFiscal();
                var res = notas.Where(y => y.ClienteID == part.ParticipanteId).Sum(o => o.ValorTotalNota);
                x.ClienteID = part.ParticipanteId;
                x.ValorTotalNota = res;
                x.NomeCliente = part.NomeParticipante;
                lista.Add(x);

            }

            dashboard.NotasFiscais = lista.OrderByDescending(x => x.ValorTotalNota).ToList();

            for (var i= 0; i < 4; i++)
            {
                lista.ToList();
            }

            return View(dashboard);



        }
    }
    
asked by anonymous 28.05.2018 / 16:00

1 answer

2

There is the Take method where you can pass a parameter that is the amount of records that will be returned from the list; As commented by Virgilio.

lista.Take(5).ToList().;

Using Take before ToList prevents you from loading the whole list into memory;

Editing for your code:

dashboard.NotasFiscais = lista.OrderByDescending(x => x.ValorTotalNota).Take(5).ToList();

So eliminating your last For

   for (var i= 0; i < 4; i++)
            {
                lista.ToList();
            }
    
28.05.2018 / 16:03