Linq with jagged arrays RRS feed

  • Question

  • User-382098719 posted

    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:

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

    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:

    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!

    Wednesday, June 19, 2019 6:22 PM

All replies

  • User753101303 posted


    String.Join is to concatenate all values taken from an array with the given separator..It should output something such as :

    Peter | 25 | 5.00
    George | 34 | 6.00
    Marry | 28 | 5.49

    (seems easy to create a console app to test that with the exact input parameters you want). Edit: forgot the sort, the ordering is likely George, Marry, and Peter...

    Edit2: while I'm at it you could just test yourself what yoou get with a test console app such as :

    using System;
    using System.Linq;
    namespace ConsoleDemo
        class Program
            static void Main(string[] args)
                string[][] jaggedArray = {
                    new string[]{"name", "age", "grade"},
                    new string[] { "Peter", "25", "5.00" },
                    new string[] { "George", "34", "6.00" },
                    new string[]{"Marry", "28", "5.49"} };
                const int headerIndex = 0;
                foreach (var row in jaggedArray.Skip(1).OrderBy(r => r[headerIndex]))
                    Console.WriteLine(string.Join(" | ", row));

    Wednesday, June 19, 2019 9:08 PM
  • User-1764593085 posted

    Hi kaloyan,

    Since it is jaggedArray, then `row` is a string[] variable in the foreach loop which corresponds to each row of the jaggedArray.

    Use OrderBy(r=>r[columnIndex]) to sort the specific column, refer to here.In the case, it will sort name column by initials.

    Use String.Join(String separator, params String[] value); to concatenates the elements of a string array, using the specified separator between each element, refer to here. In the case, it return the  Peter | 25 | 5.00

    Thursday, June 20, 2019 7:00 AM