1

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!

EL02
  • 282
  • 2
  • 9

1 Answers1

2
  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);
   }
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116
  • 1
    ah seems pretty simple. Kinda prefer the for loop over foreach. Thanks a lot anyway! – EL02 Dec 07 '21 at 23:52
  • 1
    @GL02 foreach is useful for lists or working with classes, I prefer for -for- others things. Or you need for instead foreach if you need to change the property of some item. – Leandro Bardelli Dec 07 '21 at 23:54
  • 1
    @GL02 If my answer solves your doubt, please don't forget to mark it as correct :) – Leandro Bardelli Dec 07 '21 at 23:56
  • 1
    Yeah, I'm coming from C and I still need some practice with classes and such. I had a completely different understanding of lists in c#. Gotta wait 5 more minutes to be marked as correct :) – EL02 Dec 07 '21 at 23:57
  • @GL02 seems pretty fair. BTW, don't do that all folks in C# does.... do NOT forget C or C++ !!!! Sometimes is always more simple back to the basics – Leandro Bardelli Dec 07 '21 at 23:58
  • btw shouldn't it be "i < users.Count" ? – EL02 Dec 08 '21 at 00:10
  • @GL02 you have 2 methods to get the "lenght" of something, it depends on what are you working and for what. Count will give the number of elements inside of a vector (can be an array, a list, a dictionary) and Lenght will be return the lenght of the vector, like somestring.Lenght will return the number of chars. Pretty similar – Leandro Bardelli Dec 08 '21 at 00:16
  • 1
    @GL02 https://stackoverflow.com/questions/13685541/differences-between-array-length-and-array-count – Leandro Bardelli Dec 08 '21 at 00:17