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'
}
}
}
}
nameshould 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.var age= People[i].Agesetsageto be anint. So if you want to print theagejust useConsole.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 youriis greater than the length of the name, this will also throw an error