0

Look at the code below. I have a foreach loop inside another one, but when I run the page rows repeats. Is there any way to stop repeat of rows. Here's the code and the result:

![<div class="itemContent">
<table cellspacing="0" cellpadding="0" class="productspecstable" style="float: right">
    <tbody>
        <!-- B:07L -->
        @foreach(var row in select)
        {
            foreach(var rows in selects)
            {
                <tr>
                    <td>@rows.Specifications</td>
                    <th>@row.LaptopOptions</th>
                </tr>
            } 
        }
   </tbody>
</table>
</div>

enter image description here

2
  • 3
    Generally the inner loop is dependent upon the outer one .. Commented Aug 4, 2012 at 17:20
  • What are you expecting it to do? Commented Aug 4, 2012 at 17:31

3 Answers 3

1

I'm not entirely sure what you're trying to achieve with the final layout, but from your image, I think you're looking for something along the lines of showing a header for the Specification and then all of the Laptop Options. If this is the case, then you'll need something like:

@foreach(var row in select){

    <tr>
        <th>@row.LaptopOptions</th>
    </tr>

    foreach(var rows in selects){

        <tr>
            <td>@rows.Specifications</td>
        </tr>

    } 
}
Sign up to request clarification or add additional context in comments.

Comments

1

The inner loop is repeated for each iteration of the outer loop. However, you cannot iterate synchronously over two lists, because foreach only cares about one, and inside that loop, you dont really know where in the list you are (so you cannot sync with the second list).

Possible solutions:

1) if the select[s] can be accessed with index, use one for loop to iterate over both (provided they are sorted the same way):

for(int idx=0;idx<select.Count;idx++)
{
  ...
  @select[idx].Specifications
  ...
  @selects[idx].LaptopOptions
  ...
}

2) try to reduce to one select with several values (in the code before the posted code), then you only need one foreach loop:

foreach (var row in select)
{
  ...
  @row.Specifications
  ...
  @row.LaptopOptions
  ...
}

1 Comment

Considering Metro Smurf's answer - you might want to filter the values in the inner loop to only print the values for a certain row type (so you only list specifications for the current option). My Answer is only valid if the two lists contain the same number of items; i.e. if there cannot be more than one option for each spec
0

The inner loop must be your outer loop because a laptop option can have multiple spec

          foreach(var rows in selects){
foreach(var row in select){

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.