1

I have this code for displaying a list from an array:

<table cellpadding="0" cellspacing="5" border="0" class="listTable">
@foreach(var row in list){
    <tr>
        <td>@row[0]</td>
        <td>@row[1]</td>
        <td>@row[2]</td>
        <td>@row[3]</td>
    </tr>
}
</table>

What I want is to sort the array "list" by index 3 in an ascending order before showing the list.

I have searched for hours now, because I was sure this had been adressed before, but I found nothing. Could be that I am using wrong terms when searching, if so then please point me in the right direction.

2

1 Answer 1

7

SImply use Enumerable.OrderBy<T>()

<table cellpadding="0" cellspacing="5" border="0" class="listTable">
@foreach(var row in list.OrderBy(i=>i[3])){
    <tr>
        <td>@row[0]</td>
        <td>@row[1]</td>
        <td>@row[2]</td>
        <td>@row[3]</td>
    </tr>
}
</table>
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this works perfectly. Well, almost - the third index is a number so it has to be like this: foreach(var row in list.OrderBy(i=>Convert.ToInt64(i[3]))){ otherwise it will make 100 come before 2 etc. I should have said the third index was numeric :P

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.