Question

I have the following code:

var newList = from user in allUsers.ToList()
                       select new
                       {
                           user.FirstName,
                           user.LastName,
                           user.Email,
                           Phone = SomeFunction(user.Data).Phone,
                       };

And sometimes the SomeFunction() returns a null object, then when I try to use .Phone on it, it throws a NullReferenceException.

Is there a way to catch only that item in the loop and skip it and proceed to the next element instead of skipping on the entire loop?

Was it helpful?

Solution

You could assign null(or a default number) as phone, the let clause in a query is useful to prevent multiple evaluation:

var newList = from user in allUsers.ToList()
              let data = SomeFunction(user.Data)
              select new
              {
                  user.FirstName,
                  user.LastName,
                  user.Email,
                  Phone = data == null ? null : data.Phone,
              };

Another option is to encapsulate the logic to retrieve the phone from a user in a method. You could even use a real try/catch if necessary:

private string GetPhone(User user)
{
    if (user == null)
        return null;
    return user.Phone;
}

// ...

var newList = from user in allUsers.ToList()
              select new
              {
                  user.FirstName,
                  user.LastName,
                  user.Email,
                  Phone = GetPhone(user)
              };

Last, with method syntax you could also use a statement lambda where you can use any code you want (at the cost of readability):

var newList = allUsers.ToList()
    .Select(user =>
    {
        var data = SomeFunction(user.Data);
        return new
        {
            user.FirstName,
            user.LastName,
            user.Email,
            Phone = data == null ? null : data.Phone
        };
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top