Search code examples
asp.net-mvcforeachrazor-2

Using 2 foreach in the same time in asp.net mvc razor


I want to execute 2 foreach loops at the same time. I've tried:

@foreach (var item in ViewBag.historiques) && foreach (var elt in ViewBag.statuts)
                        { .... @item  => @elt .......
}

But that didn't work. Is it possible?


Solution

  • If you're willing to give them type values you can use Linq's Zip method:

    @{
        var historiques = ViewBag.historiques as List<Historique>;
        var statuts = ViewBag.statuts as List<Statut>;
        var resultats = historiques.Zip(statuts, (item, elt) => new { item = item, elt = elt });
    }
    
    @foreach (var resultat in resultats)
    {
        <div>@resultat.item</div>
        <div>@resultat.elt </div>
    }
    

    That being said, I would recommend creating a ViewModel and building what you need in that, as opposed to using a ViewBag.