Home > other >  How do chain a null check in string.Select in c#
How do chain a null check in string.Select in c#

Time:03-31

I wanted to join object values as a comma separated string which I have done using Join, but this does not null check for each object. If I have to add a null/undefined check, how do I chain it to join? What will be the best way to do it?

  class User{
     public Guid Id {get;set;}
     public string Description {get;set}
}

public async Task<List<string>> getUser(List<User> users)
{
 var ids = string.Join(“,”, users.Select(user=>user.Id));
 var descriptions = string.Join(“,”, users.Select(user=>user.Description));
 return new List<string> {ids,descriptions};
}

CodePudding user response:

If you want to skip nulls, so don't add them at all:

var ids = string.Join(“,”, users
    .Where(user => user != null)
    .Select(user=> user.Id));
var descriptions = string.Join(“,”, users
    .Where(user => user?.Description != null)
    .Select(user=> user.Description));

CodePudding user response:

You can perform a check within the lambda expression, as it is a typical function body (just using shorthand).

 var descriptions = string.Join(",", users.Select(user => user?.Description ?? string.Empty));

If you want to be more expressive:

 var descriptions = string.Join(",", users.Select(user => string.IsNullOrEmpty(user?.Description) ? string.Empty : user.Description));
  • Related