Home > Software engineering >  C# - How to return user(object) from a list of users(objects), if user input matches email and passw
C# - How to return user(object) from a list of users(objects), if user input matches email and passw

Time:10-29

Trying to create a login function to return user from a list of users if the inputted information matches the user.

Currently have a list of users with each user having a name, email and password.

List<User> users = new List<User>();

// my user register function
public User Register_User(string a_name, string a_email, string a_pwd)
{
    User user = new User(a_name, a_email, a_pwd);
    users.Add(user);
    return user;
}

// the login function trying to implement
public void login()
{
    string email;
    string pwd;

    Console.WriteLine("\nPlease enter your email address");
    email = Console.Readline();

    Console.WriteLine("\nPlease enter your password");
    pwd = Console.Readline();

    // check if email and pwd matches a user in users
    // return the user

}

I'm just not sure on how to check if both of the user input matches a user in a list of users and return the user.

CodePudding user response:

Simple :- Use FirstOrDefault to find the user, and return it.

public User login()
{
    string email;
    string pwd;

    Console.WriteLine("\nPlease enter your email address");
    email = Console.ReadLine() ?? string.Empty;

    Console.WriteLine("\nPlease enter your password");
    pwd = Console.ReadLine() ?? string.Empty;

    // check if email and pwd matches a user in users
    var user = users.FirstOrDefault(x => x.Email.Equals(email));
    if (user == null)
        throw new InvalidOperationException("Unable to find any user!");

    // return the user
    return user;
}

Better alternative :- Use a dictionary to store users, and find the user in O(1) at runtime.

Dictionary<string, User> users = new Dictionary<string, User>();

// my user register function
public User Register_User(string a_name, string a_email, string a_pwd)
{
    User user = new User(a_name, a_email, a_pwd);
    users.Add(a_email, user);
    return user;
}

// the login function trying to implement
public User login()
{
    string email;
    string pwd;

    Console.WriteLine("\nPlease enter your email address");
    email = Console.ReadLine() ?? string.Empty;

    Console.WriteLine("\nPlease enter your password");
    pwd = Console.ReadLine() ?? string.Empty;

    // check if email and pwd matches a user in users
    if (users.ContainsKey(email))
    {
        // return the user
        return users[email];
    }

    throw new InvalidOperationException("Unable to find any user!");
}

Note :- I would suggest storing users in the database and using a data context, or repository pattern to find the user. This will delegate the task of finding the user to the database, where it should ideally belong.

  • Related