0

I am getting confused to understand the multiple dimensional array. I am having three data(strFname,strLname,strMname).

I need to put this data in a multi dimensional array.There could be n number of rows. But for each row these three data I need to add.

1

2 Answers 2

8

That could be a string[,]:

    string[,] data = new string[4, 3] {
        {"a","b","c"},
        {"d","e","f"},
        {"g","h","i"},
        {"j","k","l"}
    };

However, I would advise you create a type with the expected properties, and have a List<T> of that type - much easier to understand:

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleName { get; set; }
}
...
List<Person> people = new List<Person>();
people.Add(new Person {FirstName = "Fred", ... });
Sign up to request clarification or add additional context in comments.

Comments

5

I don't think you should use a multi-dimensional array here - I think you should encapsulate the three values in a type - something like this (assuming I've interpreted the names correctly):

public sealed class Name
{
    private readonly string firstName;
    private readonly string lastName;
    private readonly string middleName;

    // Consider changing the ordering here?
    public Name(string firstName, string lastName, string middleName)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.middleName = middleName;
    }

    public string FirstName
    {
        get { return firstName; }
    }

    public string LastName
    {
        get { return lastName; }
    }

    public string MiddleName
    {
        get { return middleName; }
    }
}

Then you can use a List<Name> or a Name[], both of which make the purpose clear.

(Yeah, this is now basically the same as Marc's answer, except my type is immutable :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.