Reputation: 13
I have this:
public class accounts
{
private string mName;
private string mEmail;
private string mAddress;
public accounts(string Name,
string Email,
string Address)
{
this.mName = Name;
this.mEmail = Email;
this.mAddress = Address;
}
}
then, somewhere else, I create this:
private static List<accounts> mlocalaccountList = new List<accounts>()
then I fill it like this:
mlocalaccountList.Add(new accounts("John Smith","[email protected]","CA USA"));
Now, everything is OK, except, how can I access the list<> items??
Upvotes: 1
Views: 379
Reputation: 6920
foreach (accounts a in mlocalaccountList) { /* do something */ }
will iterate through the list.
Upvotes: 4
Reputation: 28376
Just combining the list of everyone's answers here so far:
mlocalaccountsList[i]
will return the i'th element (0-based index, of course)foreach(var account in mlocalaccountList)
will easily provide you with each element in turn.Use a LINQ query to filter out a specific element in the list. LINQ has two different styles of writing queries:
var result = mlocalaccountList.Where(a => a.Name == "John Smith"))
// or
var result = from a in mlocalaccountList
where a.Name == "John Smith"
select a;
Upvotes: 1
Reputation: 24385
You can access them in a foreach loop:
foreach (var item in mlocalaccountList) {
...
}
however, since all members are private you cannot access them at all. Consider making properties for the private members or making them public.
You can also access them by index:
mlocalaccountList[0]
is the first item in the list.
Upvotes: 4
Reputation: 137118
Here's a link to the List<T>
MSDN page. The Members page lists all the methods and properties that you have available. You can find help on ForEach
for example.
The MSDN library (http://msdn.microsoft.com/en-us/library/) is an invaluable source of information on the classes and their members.
Upvotes: 1
Reputation: 5058
I would recommend using a foreach
statement or just access by using an index
variable mlocalaccount[index]
Upvotes: 2
Reputation: 46415
You can iterate over them:
foreach (var item in mlocalaccountList)
{
// do stuff with item
}
You can use LINQ:
var usaItems = mlocalaccountList.Where(a => a.Address.Contains("USA"));
// assuming you implement a public property for Address
Upvotes: 1
Reputation: 1772
Though I don't program in C#, I believe it is: mlocalaccountList[index]
where index is an int.
Upvotes: 0
Reputation: 3621
Try mlocalaccountList[0]
or
foreach (accounts acct in mlocalaccountList)
{
// Do something with acct
}
Upvotes: 2
Reputation: 74250
Use a foreach statement:
foreach (accounts acc in mlocalaccountList)
{
... do something with acc
}
Upvotes: 0