skip to Main Content

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

2

Answers


  1. 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));
    
    Login or Signup to reply.
  2. 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));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search