简体   繁体   中英

Multiple arraylist into a multi-dimensional array

Hello I was wonder if there was any ways I could merge multiple arraylist into a multi array.

Exmaple

I have arraylist1 which holds names. arraylist 2 which holds phone number and arraylist 3 which holds address. how could i merge these into one multi array so it would be as a record?

Lets suppose you have three ArrayList of string and all elements at ith index forms a record,

ArrayList Names = new ArrayList();
ArrayList Phone = new ArrayList();
ArrayList Address = new ArrayList();
ArrayList res = new ArrayList();

for(int i=0; i<Names.Count; i++)
{
  res.Add(new string[]{Names[i].ToString(), Phone[i].ToString(), Address[i].ToString()});
}

Are the contents of these ArrayLists related in some way, such as contacts?

If so, consider creating a class to represent a single contact. This contact class can have Name, PhoneNumber, and Address properties. You can even use a collection for each of these properties in case more than one would apply to a given contact record.

You can store your different contact records into an ArrayList, or if you're using .NET 2+ a strongly typed List.

If you are operating in .NET 4.0 you should use List<T> though you could still do this with ArrayList too if you like. But you could take advantage of the Tuple to combine your types easily (though I totally agree with the suggestions to create a custom class to hold the "record"):

    List<string> phones = new List<string>();
    List<string> addresses = new List<string>();
    List<string> names = new List<string>();

    // fill with data

    List<Tuple<string,string,string>> results = new List<Tuple<string, string, string>>();

    // aggregate with data - if only two you could also use Zip()
    for (int i = 0; i < names.Count; i++)
    {
        results.Add(Tuple.Create(names[i], addresses[i], phones[i]));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM