Mister98
Mister98

Reputation: 69

Linq within a for loop

I have this action in my controller:

    public async Task<IActionResult> RiceviListaSpesa([FromBody]List<Prova> ListaAcquisti)
    {

        for (int i = 0; i < ListaAcquisti.Count; i++)
        {
            DateTime dt = Convert.ToDateTime(ListaAcquisti[i].Scadenza);
            var result = await _context.ProdottiMagazzino.SingleOrDefaultAsync(p => p.Prodotto.Codice == ListaAcquisti[i].Codice && p.Scadenza == dt);

        }
        // result = all the row ??
        return (View());
    }

What I would do is assign to a variable all the results generated from the query within the loop, to use them outside of the loop

Upvotes: 0

Views: 69

Answers (1)

yoger
yoger

Reputation: 282

Have you considered following:

public async Task<IActionResult> RiceviListaSpesa([FromBody]List<Prova> ListaAcquisti)
{
    var results = new List<YourResultType>();
    for (int i = 0; i < ListaAcquisti.Count; i++)
    {
        DateTime dt = Convert.ToDateTime(ListaAcquisti[i].Scadenza);
        var result = await _context.ProdottiMagazzino.SingleOrDefaultAsync(p => p.Prodotto.Codice == ListaAcquisti[i].Codice && p.Scadenza == dt);
        results.Add(result);
    } 
    // do whatever you need to all the results stored in results list
    return View();
}

Upvotes: 1

Related Questions