How to get data out of an Arraylist
So in a previous quesiton I asked how i could merge multiple array list into one array list.
This answer worked (also listed below). However, I am having issues getting th开发者_Python百科e records out. How do I get the data out of this multi dimensional arraylist. For example, what if I wanted to get just address out?
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()});
}
You could do something like the following ... I want to make sure and I note that you might want to come up with better data structures or container classes if you can.
string someAddress = ((string[])res[0])[2];
In this instance we are taking the object (string array) at the first index of res
and then indexing into the string array where the address was stored.
You could consider a something like the following though to contain your data with a typed list..
public class Person
{
public string Name { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
}
...
List<Person> people = new List<Person>();
people.Add(new Person() { Name = "Not Me", Phone = "(555) 212-1234", Address = "123 Fake St." });
string address = people[0].Address;
Personally, I would make this a struct.
public struct Record
{
public String Name;
public String Telephone;
public String Address;
}
And push the information in to the structs and then re-reference them. Something like:
ArrayList records = new ArrayList();
for (...) {
records.Add(new Record(){
Name = Names[i].ToString(),
Telephone = Phone[i].ToString(),
Address = Address[i].ToString()
});
}
...
Console.WriteLine(records[0].Address);
Assuming this is .NET 2.0 and not anything later so you have to stick with ArrayList
, I would just introduce a new class to hold your information.
public class Person
{
private string _name;
public string Name { get { return _name; } }
public Person(string name, string phone, string adress)
{
_name = name;
...
}
}
Then you can populate instances of this class in your arraylist and access its properties.
Can I ask why you are creating array lists like you are? In my opinion, you're better off to create a custom object that has 3 properties -> Name, Phone and Address, and simply create a list of those objects:
Resident class:
public class Resident
{
public string Name { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
}
Code:
List<Resident> residents = new List<Resident>();
// populate list
foreach (var res in residents)
Console.WriteLine(res.Address);
精彩评论