Click here to Skip to main content
15,884,821 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to understand a piece of code but I am not sure I do. I will be very grateful if someone could explain to me what happens here:

C#
foreach (var row in jaggedArray.Skip(1).OrderBy(r => r[headerIndex]))
{
    Console.WriteLine(string.Join(" | ", row));
}


What I have tried:

I suggest that .Skip(1) misses the first row, but after that, I did not understand anything. I will give you an example of what this code does:

4
name, age, grade
Peter, 25, 5.00
George, 34, 6.00
Marry, 28, 5.49
sort name

This is an example input. Our jagged array has 4 rows and 3 columns. We have to sort the name header so in this case, the header index is equal to 0. Thank you advance!
Posted
Updated 19-Jun-19 8:24am

1 solution

OrderBy orders all elements in an enumerable by a certain key. In your example, the "elements" are arrays, and the "key" is the Nth element in the array (where N depends on headerIndex).

Here's an example:
C#
object[][] jaggedArray = new object[][] {
    new object[] { "Apples", 3.5, 200 },
    new object[] { "Bananas", 4.8, 50 },
    new object[] { "Ananas", 5.7, 75 }
}; // array of items in a store, with their name, price, and number in stock

var headerIndex = 0; // 0 for name, 1 for price, 2 for stock
foreach (var row in jaggedArray.Skip(1).OrderBy(r => r[headerIndex]))
{
    Console.WriteLine(string.Join(" | ", row));
}
This prints:
Ananas | 5.7 | 75
Bananas | 4.8 | 50
Because the first item, Apples, gets skipped, and the other items are sorted by r[headerIndex] (which is r[0] in the example, so the item name).
 
Share this answer
 
Comments
Member 14422952 19-Jun-19 14:50pm    
But how the other columns are saved? I mean the apple is still corresponding with its price and number in stock.
Thomas Daniels 19-Jun-19 14:58pm    
OrderBy merely specifies how to order, but the elements itself as in jaggedArray.Skip(1) are kept as-is.
Member 14422952 19-Jun-19 15:01pm    
If I understand we say 'order the table by name' and OrderBy() saves the corresponding items, don't we?
Thomas Daniels 19-Jun-19 15:06pm    
I'm not sure what you mean by "saves".

What OrderBy does is: it receives a collection. In this case, that's jaggedArray.Skip(1). It sorts the elements by the way you specified and returns that.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900