1

To simplify, let's say I have a method that should return a User object from an ID found in a list of users. If no user is found I want to throw an Exception.

My current code works:

public User GetUserFromID(int id)
{
    foreach (User u in Users)
        if (u.id == id)
            return u;
    
    throw new Exception("No user is found");
}

But my problem comes when I want to find a user with a lambda expression instead of the foreach loop. The following code succeeds in returning the correct User object but never throws an exception if nothing is found.

public User GetUserFromID(int id)
{
    return Users.Find(u => u.id == id);
    
    throw new Exception("No user is found");
}
0

2 Answers 2

1

You could use User.Single(...) which would throw an exception if there isn't exactly one match:

public User GetUserFromID(int id)
{
    return Users.Single(u => u.id == id);
}

Just for completeness, if you wanted to throw your own exception, then you could do something like this.

Using SingleOrDefault will return null if there is no match or if there is more than 1 match, so you can check for null to determine if an exception should be thrown:

public User GetUserFromID(int id)
{
    var user = Users.SingleOrDefault(u => u.id == id);

    if(user == null)
        throw new Exception("No user is found");
 
    return user;
}
Sign up to request clarification or add additional context in comments.

Comments

0
public User GetUserFromID(int id)
{
    return Users.Single(u => u.id == id);
}

Users.Single will throw an exception when there is not exactly one match.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.