Home > other >  Iterate through list objects to find object with matching property value
Iterate through list objects to find object with matching property value

Time:05-30

I have a list of objects (users) of a class (User). Now I try to retrieve the (unique) object that has a certain property value (for example string username = name). So what needs to be returned is the object, based on the value of its property.

There are several similar questions asked here, but none seem to return the object as a whole.

I've tried several methods including this one:

public User GetUser(string name)
{
    User currentUser;

    for(int i = 0; i < this.users.Count; i  )
    {
        if (users[i].GetName().Equals(name))
        {
            users[i] = currentUser;
        }
    };

    return currentUser;
}

A problem here is that currentUser is not accepted as a variable. What would be a better way to go about this?

CodePudding user response:

You can use LINQ:

public User GetUser(string name)
{
    return users.FirstOrDefault(x => x.GetName().Equals(name));
}

Note: if such a name does not exist, the default will be returned, the default for this case isnull.

CodePudding user response:

A quick way to get what you want is to use LinQ

var user = users.Where(user => user.GetName() == name).First();

or shorter

var user = users.First(user => user.GetName() == name);

CodePudding user response:

It seems you are trying to do this

var user = users.FirstOrDefault(u => u.GetName().Equals(name));

CodePudding user response:

use the getter for username in the User object in place of GetName

public User GetUser(string name)
{
   return users.FirstOrDefault(u => u.GetName().Equals(name));
}


CodePudding user response:

//     is optional, if you want ignore case
// users[i].GetName().Equals(name, StringComparison.InvariantCultureIgnoreCase)
public User? GetUser(string name)
{
    for(int i = 0; i < this.users.Count; i  )
        if (users[i].GetName().Equals(name))
            return users[i]; // early-return pattern
    return null; // returns null if no such user found
}

Dont forget to check for null in client code:

var user = GetUser("SomeUserName");
if(user is null) {
    // do some
}

And if you like to use linq:

public User? GetUser(string name) => users.FirstOrDefault(u => u.GetName().Equals(name));
  • Related