Reputation: 1
I'm currently learning c#, and i'm trying to make a script that create a bank account and then find it back and add money on it.
This method is used to create a new account :
static void CreateNewAccount()
{
Console.WriteLine("Enter a name for a new account.");
string bname = Console.ReadLine();
Console.WriteLine("Creating a new account for : {0}", bname);
List<BankAccount> account = new List<BankAccount>() // not sure about it
{
new BankAccount { name = bname } // creating a new account
};
Console.WriteLine(account.Exists(x => x.name == bname));
var useraccount = account.Find(x => x.name == bname); // Trying to find the account that i've created earlier
useraccount.Deposit(100); // trying to add money on it
useraccount.CheckBalance();
Console.WriteLine("test");
}
And here is my class :
class BankAccount
{
private double _balance=0;
public string name;
public BankAccount()
{
Console.WriteLine("You succesfuly created a new account.");
}
public double CheckBalance()
{
return _balance;
}
public void Deposit(double n)
{
_balance += n;
}
public void WithDraw(double n)
{
_balance -= n;
}
}
I'm not sure at all about how to use List and how to use Find. I writed this because i've it found on a similar script.
Do you know a easy way to make it ? I'm a beginner.
Thanks
Upvotes: 0
Views: 2023
Reputation: 34421
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
}
static void CreateNewAccount()
{
Bank bank = new Bank();
Console.WriteLine("Enter a name for a new account.");
string bname = Console.ReadLine();
Console.WriteLine("Creating a new account for : {0}", bname);
BankAccount account = new BankAccount(bname, 0);
Console.WriteLine(bank.GetAccounts().Exists(x => x.name == bname));
var useraccount = bank.GetAccount(bname); // Trying to find the account that i've created earlier
useraccount.Deposit(100); // trying to add money on it
useraccount.CheckBalance();
Console.WriteLine("test");
}
}
class Bank
{
private List<BankAccount> accounts = new List<BankAccount>();
public List<BankAccount> GetAccounts()
{
return accounts;
}
public BankAccount GetAccount(string name)
{
return accounts.Where(x => x.name == name).FirstOrDefault();
}
}
class BankAccount
{
private double _balance = 0;
public string name;
public BankAccount(string name, double balance)
{
this.name = name;
this._balance = balance;
Console.WriteLine("You succesfuly created a new account.");
}
public double CheckBalance()
{
return _balance;
}
public void Deposit(double n)
{
_balance += n;
}
public void WithDraw(double n)
{
_balance -= n;
}
}
}
Upvotes: 0
Reputation: 993
You could use LINQ to find a certain object in a list.
var query = account.Where(a => a.name == "A NAME" );
Then to use this
foreach(var account in query.ToList())
{
//do work
}
Upvotes: 1