简体   繁体   中英

How to display the contents of a class which is generic list, by foreach loop?

I want to display the contents of collection in list by foreach loop but variables (name) and (age) do not match in foreach loop.

string name;
float age;
List<universe> collection = new List<universe>();
universe main = new universe();
for (int i = 0; i < 10; i++)
{
    Console.WriteLine("name");
    name = Console.ReadLine();
    Console.WriteLine("age");
    age = float.Parse(Console.ReadLine());
    main.Galaxy(name, age);
    collection.Add(main);
}
foreach (universe b in collection) 
{
    Console.WriteLine(main.Galaxy(name, age));
}

I've tried to make a list of (main) but I coudn't.

Try something like this:

string name;
float age;
List<universe> collection = new List<universe>();

for (int i = 0; i < 10; i++)
{
    universe main = new universe();

    Console.WriteLine("name");
    name = Console.ReadLine();
    Console.WriteLine("age");
    age = float.Parse(Console.ReadLine());
    main.Galaxy(name, age);
    collection.Add(main);
}

foreach (universe b in collection) 
{
    Console.WriteLine($"{b.Name} {b.Age}"); // <== I don't know if universe class has Name and Age properties
}

Use this

static void Main(string[] args)
    {
        string name;
        float age;
        List<universe> collection = new List<universe>();
        universe main = new universe();
        for (int i = 0; i < 2; i++)
        {
            Console.WriteLine("name");
            name = Console.ReadLine();
            Console.WriteLine("age");
            age = float.Parse(Console.ReadLine());
            main.Galaxy(name, age);
            collection.Add(main);
        }
        foreach (universe b in collection)
        {
            Console.WriteLine("name =" + b.Name + " Age=" + b.Age);
        }
        Console.ReadKey();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM