简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM