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!

5
  • 2
    Why not use a class to keep the data for each thing together? Commented Dec 7, 2021 at 23:50
  • 1
    users[0] is the first list entry, and users[0][0] is the first item in the first list entry: the name. Commented Dec 7, 2021 at 23:50
  • 1
    @ŇɏssaPøngjǣrdenlarp For now I'm still learning the basics, but I do get what you're saying Commented Dec 7, 2021 at 23:53
  • 1
    @PeterB okay, I got it now. Thanks! Commented Dec 7, 2021 at 23:53
  • I just updated my answer to show you how to work with classes Commented Dec 7, 2021 at 23:56

1 Answer 1

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);
   }
Sign up to request clarification or add additional context in comments.

8 Comments

ah seems pretty simple. Kinda prefer the for loop over foreach. Thanks a lot anyway!
@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.
@GL02 If my answer solves your doubt, please don't forget to mark it as correct :)
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 :)
|

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.