Home > Software design >  Access individual arrays or element of array when the array is an element of a list C#
Access individual arrays or element of array when the array is an element of a list C#

Time:12-08

I'm pretty new to C# and cannot figure out how to print the first array element of the list. The code to print all array elements is this:

using System.Collections.Generic;

class Program1 {
  static List<string[]> users = new List<string[]>();
  static void Main() {
  users.Add(new string[]{"Ben", "21", "Germany"});
  users.Add(new string[]{"Tom", "32", "Finland"});

  foreach(var person in users){
      Console.WriteLine($"Name: {person[0]}, Age: {person[1]}, Country: {person[2]}");
   }
  }
}

Like how can I only print the first array or the first item in the first array and so on? Any help/tip would be really helpful!

CodePudding user response:

  for(int i = 0; i < users.Lenght();i  ) {
      Console.WriteLine($"Name: {users[i][0]}, Age: {users[i][1]}, Country: {users[i][2]}");
   }

Or better with a class:

public class User {
    public string Name {get;set;}
    public int Age {get;set;}
    public string Country {get;set;}
}

and then:

List<User> users = new List<User>();

  foreach(User myUser in users){
      Console.WriteLine(myUser.Name);
      Console.WriteLine(myUser.Age);
      Console.WriteLine(myUser.Country);
   }
  • Related