How do this FOR (in C#) list only the first five items?

Asked

Viewed 156 times

0

I have an orderly list, which I need to display only the first 5 items, not all bank records, so I’m not getting it. Here’s my code as 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);



        }
    }

1 answer

2


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

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

Using the Take before the ToList you avoid loading into the memory of the entire list;

Editing for your code:

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

Thus eliminating your last For

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

    ToList().Take(5) cause the full loading of the table after in mémoria handle 5, it is better lista.Take(5).ToList() ???

  • Yes, it would be better to use Take(5). Tolist(); Thanks for the correction.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.