Reputation: 323
I have a list that stores objects from different Account classes. I have a method that allows lodgements to accounts. The user enters the account Id and the ID and my list are passed to another method, which searches the objects to see if that account exists. I want it to then return the account details back to the lodgement method.
I can't figure out how to return the object from the search method.
My list looks like this List<Account> bank;
I have this assignment done in C++ and I've just start C#, and finding it hard to get used to it. Any help would be appreciated!
My list looks like this List<Account> bank;
I have this assignment done in C++ and I've just start C#, and finding it hard to get used to it. Any help would be appreciated!
Edited to include my code, which doesn't work.
public static void processLodgement(List<CAccount> bank)
{
CAccount p;
string ID;
double amount = 0;
Console.WriteLine("Process Lodgement\n");
Console.WriteLine("Enter account ID\n");
ID = Console.ReadLine();
Console.WriteLine("Enter Lodgement Amount\n");
double.TryParse(Console.ReadLine(), out amount);
findAccount(bank, ID);
}
public static CAccount findAccount(List<CAccount>bank, string accountID)
{
for(int i=0; i < bank.Count(); i++)
{
if (bank[i].GetID()==accountID)
{
return bank[i];
}
}
}
Upvotes: 1
Views: 138
Reputation: 14153
You need to use the id
and list of accounts as parameters, and an Account
as your return type.
public Account FindAccount(int id, List<Account bank)
{
// Look for account based on ID or do something, and return the account.
}
For example, you could use LINQ to search for the account:
return bank.FirstOrDefault(acc => acc.ID == id);
Or just use a loop:
foreach (var acc in bank)
{
if (acc.ID == id)
return acc;
}
// Handle account not found.
Edit: In response to your posted code, this is how it should look.
public static CAccount findAccount(List<CAccount>bank, string accountID)
{
for(int i=0; i < bank.Count; i++)
{
if (bank[i].GetID() == accountID)
{
return bank[i];
}
}
throw new Exception("Account not found!");
}
At the end of your method, you need to return something (such as null), or throw an error. Also, use Count
instead of Count()
for better performance (Count()
is for LINQ queries)
Upvotes: 1