khalidabuhakmeh / ConsoleTables

Print out a nicely formatted table in a console application C#
MIT License
948 stars 158 forks source link

Add simple SortBy (with code) #53

Closed ricardok1 closed 1 year ago

ricardok1 commented 3 years ago

Hi there

I'm seeing this library and thanks for making available for all. I suggest to add a new option to output with some Sort selected by Column index. KISS. No fuzz.

Modified to be the less intrusive possible and automatically for every output.

Usage:

Table.Options.SortByColumn = 1;  // index base zero of columns
Table.ToString(); // whatever output  due getter modification

Rows:

            private IList<object[]> _Rows { get; set; }
            public IList<object[]> Rows 
            {
                get
                {
                    if (Options.SortByColumn == -1)
                    {
                        return _Rows;
                    }
                    else if (Options.SortByColumn < Columns.Count)
                    {
                        return _Rows.OrderBy(w => (string)w[Options.SortByColumn]).ToList();
                    }
                    else
                    {
                        throw new Exception("Invalid ConsoleTable.Options.SortByColumn: " + Options.SortByColumn);
                    }
                }

                protected set
                {
                    _Rows = value;
                }

            }

Options:

 public class ConsoleTableOptions
    {
(,,,)
        /// <summary>
        /// Sort by Column Index  (no sort = -1 )
        /// </summary>
        public int SortByColumn { get; set; } = -1;
(...)
    }

Please check anf if you agree add it to your code.

Thanks Ricardo

khalidabuhakmeh commented 1 year ago

If you want to sort the data, you probably should do it before outputting to the table. I think it would also be more performant.