0

trying to brush up my foundation on C#. How do I print the value of objects from a List? I have a List and wants to print out the Name and Age to console.

I can use foreach loop to print them out easily with whole name and age but I am just curious how to do it through a for loop here is my code which I fail of coz Thank you for your opinion and help

namespace Rextester
{
    public class Person
    {
        
        public string Name {get;set;}
        public int Age {get; set;}

    }
    public class Program
    {
        public static void Main(string[] args)
        {
            
            
            var People = new List<Person>
            {
                new Person{Name ="mary", Age= 60},
                new Person{Name ="john", Age = 40},
                new Person{Name ="peter", Age= 50},
                new Person{Name ="jane", Age=30}
            };

            foreach(var obj in People)
            {
                Console.WriteLine(obj.Name + obj.Age);
            }
            
            for(int i=0; i<People.Count; i++)
            {
                var name = People[i].Name;
                var age = People[i].Age;
                Console.WriteLine(name[i]); // result is char in each index of string m, o ,t, e  instead of name - mary, john, peter, jane
                Console.WriteLine(age[i]);// error: Cannot apply indexing with [] to an expression of type 'int'
            } 
        }
    }
}
4
  • 3
    name should be a string, so you can index each letter (char) - if that is what you want. Age is an int which cant be indexed because there are no meaningful component elements. Commented Sep 3, 2021 at 16:35
  • 1
    The error says it all. var age= People[i].Age sets age to be an int. So if you want to print the age just use Console.WriteLine(age). Same for name. This doesn't throw an immediate error for the first few items, because you can access individual chars of a string via index [i]. But once your i is greater than the length of the name, this will also throw an error Commented Sep 3, 2021 at 16:36
  • @ŇɏssaPøngjǣrdenlarp thank you! that make sense :)) now i got it Commented Sep 3, 2021 at 16:56
  • @derpirscher Thank you! so i was over thinking. It is that simple.... thanks Commented Sep 3, 2021 at 16:57

1 Answer 1

3

You almost did everything by yourself:

Console.WriteLine(People[i].Name);
Console.WriteLine(People[i].Age);
Sign up to request clarification or add additional context in comments.

1 Comment

Or simply Console.WriteLine(name); and Console.WriteLine(age);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.