开发者

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]));
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜