C# collection count a certain object and print out while looping through the collection into a listbox or textbox

Viewed 34

I am newbie to C#. If I created a collection with a number of objects.

Let us say my collection looks like this:

var theGalaxies = new List<Galaxy>
{
        new Galaxy() { Name="Tadpole", MegaLightYears=400, Level=1},
        new Galaxy() { Name="Pinwheel", MegaLightYears=25, Level=1},
        new Galaxy() { Name="Milky Way", MegaLightYears=0, Level=2},
        new Galaxy() { Name="Andromeda", MegaLightYears=3, Level=3}
};

foreach (Galaxy theGalaxy in theGalaxies)
   {
       Console.WriteLine(theGalaxy.Name + "  " + theGalaxy.MegaLightYears);
   }

How can I count how many objects is categorized in respective "level" and print out the information like the following output:

Name   MegaLightYears  Level
Tadpole  400            1
Pinwheel  25            1
2 galaxies in Level 1 
Milky Way  0            2
1 galaxy in Level 2 
Andromeda  3            3
1 galaxy in Level 3 

Is there any way to print out information so it reserves a certain space for the input so the output does not look like this:

    Name   MegaLightYears  Level
Tadpole  400   1
Pinwheel  25 1

Thanks for advance

1 Answers

Modify your code as like shown below

foreach(var galaxies in theGalaxies.GroupBy(x=>x.Level)){
    foreach(var galaxy in galaxies){
        Console.WriteLine($"{galaxy.Name} {galaxy.MegaLightYears}");
    }   
    Console.WriteLine($"{galaxies.Count()} galaxies in Level {galaxies.Key}");
}

To show proper table on console use link Or below code

static int tableWidth = 73;

static void Main(string[] args)
{
    Console.Clear();
    PrintLine();
    PrintRow("Column 1", "Column 2", "Column 3", "Column 4");
    PrintLine();
    PrintRow("", "", "", "");
    PrintRow("", "", "", "");
    PrintLine();
    Console.ReadLine();
}

static void PrintLine()
{
    Console.WriteLine(new string('-', tableWidth));
}

static void PrintRow(params string[] columns)
{
    int width = (tableWidth - columns.Length) / columns.Length;
    string row = "|";

    foreach (string column in columns)
    {
        row += AlignCentre(column, width) + "|";
    }

    Console.WriteLine(row);
}

static string AlignCentre(string text, int width)
{
    text = text.Length > width ? text.Substring(0, width - 3) + "..." : text;

    if (string.IsNullOrEmpty(text))
    {
        return new string(' ', width);
    }
    else
    {
        return text.PadRight(width - (width - text.Length) / 2).PadLeft(width);
    }
}
Related