Home > database >  How do I access individual items from a list in c#?
How do I access individual items from a list in c#?

Time:10-07

I am reading customer's account information from a csv file in a basic banking program. So I am parsing the account data from a csv and converting it into class objects and then putting those objects in a list and I am trying to use a loop to retrieve this data and use it to allow customers to login and carry out transactions.

public class Account
{
    public string CustomerName { get; set; }
    public string PIN { get; set; }
    public double Balance { get; set; }

    internal static Account ParseRow(string row)
    {
        var columns = row.Split(',');

        return new Account()
        {
            CustomerName = columns[0],
            PIN = columns[1],
            Balance = double.Parse(columns[2])
        };
    }
}

public partial class Form2 : Form 
{
    public Form2()
    {
        InitializeComponent();
    }

    private static List<Account> ProcessCSV(string path)
    {
        return System.IO.File.ReadAllLines(path)
            .Skip(1)
            .Where(row => row.Length > 0)
            .Select(Account.ParseRow).ToList();
    }

    private void btnLogin_Click_1(object sender, EventArgs e)
    {
        var accounts = ProcessCSV("Accounts.csv");

        if (txtUsername.Text == "" || txtPassword.Text == "")
        {
            MessageBox.Show("Please ensure to fill in all fields");
        }

        foreach (var account in accounts)
        {
            if (txtUsername.Text == account.CustomerName)
            {
                continue;
            }
            else
            {
                lblUsername.Text = "Incorrect Username";
            }

            if (txtPassword.Text == account.PIN)
            {
                Form1 f1 = new Form1();
                f1.ShowDialog();
            }
            else
            {
                lblPassword.Text = "Incorrect Password";
            }
        }
    }
}

It seems the program is picking all the items from the list such as all customer names where account.CustomerName is concerned and so on. I just want to pick out and individual customer name and pin to validate the Login of a customer, how can I do this?

CodePudding user response:

//You can use LINQ to get the first matching account or default (null) if none found
var useraccount = accounts.FirstOrDefault(z => 
                             z.CustomerName == txtUsername.Text && 
                             z.PIN == txtPassword.Text)



if(useraccount != null)
{
    //Do something since it's valid
}
else
{
    //Do something since it's not valid
}
  • Related