0

I've got this unreachable code in this for loop

public IActionResult List(int id) {
    for (id = 0; id <= 1000; id++) {
        var fil = _repoFil.GetById(id).Result;
        var listafiliali = new List<FilialeVM>();

        foreach (var filiale in fil) {
            var filialeVM = _mapper.Map<FilialeVM>(fil);
            listafiliali.Add(filialeVM);
        }

        return View(listafiliali);
    }

    return View();
}

the increment id++ is unreachable

dbc
  • 104,963
  • 20
  • 228
  • 340
CSharper
  • 21
  • 9

3 Answers3

2

You have several problems with your code:

  1. You ignore id passed: imagine that I call List(1234), 1234 will be ignored as well as 789 in List(789)
  2. You don't loop over id since you return after the 1st loop
  3. You'll never reach return View(); code: you enter loop and return from it.

I guess, you want something like this:

  using System.Linq;

  ...

  public IActionResult List(int id) {
    // for given id we collect all corresponding FilialeVM items
    var listafiliali = _repoFil
      .GetById(id)                                // items correspond to given id
      .Result
      .Select(fil => _mapper.Map<FilialeVM>(fil)) // mapped to FilialeVM
      .ToList();                                  // organized as list

    // If we have any item in listafiliali, view them, otherwise use default View()
    return listafiliali.Any()
      ? View(listafiliali)
      : View();
  } 

Or if you don't want id to be passed but to scan id = [0..1000] range:

  public IActionResult List() {
    // for id in [0..1000] range we collect all corresponding FilialeVM items
    var listafiliali = Enumerable
      .Range(0, 1000 + 1)
      .SelectMany(id => _repoFil
         .GetById(id)                                 // items correspond to given id
         .Result
         .Select(fil => _mapper.Map<FilialeVM>(fil))) // mapped to FilialeVM
      .ToList();                                      // organized as list

    // If we have any item in listafiliali, view them, otherwise use default View()
    return listafiliali.Any()
      ? View(listafiliali)
      : View();
  } 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

It is unreachable because you have this line: return View(listafiliali); in your for loop. The method returns and terminated its execution in the first for-loop iteration as soon as it hits the before mentioned return.

Niklas7
  • 173
  • 8
0

return your View AFTER your loop finished

public IActionResult List(int id) {
    var listafiliali = new List<FilialeVM>();

    for (id = 0; id <= 1000; id++) {
        var fil = _repoFil.GetById(id).Result;            
        foreach (var filiale in fil) {
            var filialeVM = _mapper.Map<FilialeVM>(fil);
            listafiliali.Add(filialeVM);
        }            
    }

    if(listafiliali.Count > 0)
       return View(listafiliali);

    return View();
}
Sancho Panza
  • 670
  • 4
  • 11