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?

Était-ce utile?

La 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
        };
    });
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top