[英]C# collection count a certain object and print out while looping through the collection into a listbox or textbox
I am newbie to C#.我是 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:如何计算在各个“级别”中分类的对象数量并打印出如下 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:有没有办法打印出信息,所以它为输入保留了一定的空间,所以 output 看起来不像这样:
Name MegaLightYears Level
Tadpole 400 1
Pinwheel 25 1
Thanks for advance感谢提前
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.