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
};
});