Home > Software design >  How can I output the values aligned to each column name?
How can I output the values aligned to each column name?

Time:09-14

using System;
using System.Collections.Generic;
namespace freewritings
{
    internal class Program
    {
        static void Main(string[] args)
        {
            List<int> numlist = new List<int>() { 35, 30, 10, 5, 15,25, 20, 40 };

            Console.Write("Original List\t");
            Console.Write("Sorted List\t");

            foreach(var num in numlist)
            {
                Console.WriteLine(num);
            }
        }
    }
}

Expected Output:

Original List    Sorted List
35               5
30               10
10               15
5                20
15               25 
25               30
20               35
40               40

CodePudding user response:

You can use Linq OrderBy() . e.g.

List<int> numlist = new List<int>() { 35, 30, 10, 5, 15, 25, 20, 40 };
var orderedList = numlist.OrderBy(x => x).ToList();
orderedList.ForEach(x => Console.WriteLine(x));

CodePudding user response:

A good ol'e fashioned for loop is a good option here

var numlist = new List<int>() { 35, 30, 10, 5, 15, 25, 20, 40 };
var sortedlist = numlist.OrderBy(n => n).ToList();

Console.Write("Original List\t");
Console.WriteLine("Sorted List");

for (int i = 0; i < numlist.Count; i  )
{
    Console.WriteLine($"{numlist[i]}\t{sortedlist[i]}");
}
  •  Tags:  
  • c#
  • Related