0

I am trying to store data in an array like the following in a foreach loop:

firstname,lastname,dateofbirth

Therefore, once the loop has completed I should get {John,Smith,05/05/1980},{Mary,Smith,05/04/1980} etc... This will enable me to access different information for each person stored in the system.

What would be the best way to do this? I have been reading into using hierarchical arrays like those shown here http://msdn.microsoft.com/en-us/library/ms486189(v=office.12).aspx but I am not sure if this is the best method.

I am quite new to c# programming so any advice would be much appreciated!

Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121
Mike91
  • 520
  • 2
  • 9
  • 25

2 Answers2

5

The best way is to create a class to store the information.

public class Person
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public DateTime DateOfBirth {get; set;}
}

Then create a list of Person objects.

List<Person> people = new List<Person>()
people.Add(new Person() { FirstName = "John", LastName = "Smith", DateOfBirth = new DateTime(1980, 5, 5) });
Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121
  • 2
    @ Juliusz. A struct sits on the call stack. A class has a reference on the call stack. It performs better this way. Structs are better for collections of value types (e.g. System.Drawing.Point). – Paul Fleming Jul 16 '12 at 17:05
  • Thanks Kyle. However I am getting an error on the .Add (I have used this before when using lists). What do I have to do add an 'Add' definition to the class? – Mike91 Jul 16 '12 at 17:12
  • Make sure you have a `using System.Collections.Generic;` entry at the top of the file. If that doesn't fix it, can you paste the exact error message you are getting? – Kyle Trauberman Jul 16 '12 at 17:14
2

Maybe use a stucture like this:

Class to hold individual person info:

public class Person
{
 public string FirstName {get;set;}
 public string LastName {get;set;}
 public DateTime DateOfBirth {get;set;}
}

List of people:

List<Person> people = new List<Person>;
Paul Fleming
  • 24,238
  • 8
  • 76
  • 113