简体   繁体   中英

Add “ | ” in string if where string value is not null or empty

I want to add " | " in 3 string if string is not null or empty Ex.

-> UserName | Phone | Email

in case UserName is null then Phone | Email Phone | Email in case UserName and Email both are null string contain only PhoneNumber .

some thing like this

var userName =string.IsNullOrEmpty(dir.UserName)?"": dir.UserName+ " | ";
var userEmail = string.IsNullOrEmpty(dir.UserEmail) ? "" : dir.UserEmail+ " | " ;
var userphone = string.IsNullOrEmpty(dir.UserPhoneNumber) ? "" :  dir.UserPhoneNumber;
var disply = userName + userEmail  + userphone;

Can it done by linq with less code.

Try this:

string[] all = {dir.UserName, dir.UserPhoneNumber, dir.UserEmail};
string result = string.Join(" | ", all.Where(str => !string.IsNullOrEmpty(str)));

My idea would be following: After you store the three Strings in an array: 1. Check if UserName is the only String not null - If it is then just print it, else proceed to 2.

  1. Append | and Phone (Phone can't be null since 1. checks for it)

  2. If there is a element at array index 2 append a | and the Email.

  3. Done!

Side note: This will take more lines to code but it would be way more readable and simple code.

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