Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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 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.

like image 780
Shivam Mishra Avatar asked Sep 01 '25 16:09

Shivam Mishra


1 Answers

Try this:

string[] all = {dir.UserName, dir.UserPhoneNumber, dir.UserEmail};
string result = string.Join(" | ", all.Where(str => !string.IsNullOrEmpty(str)));
like image 118
Patrick Avatar answered Sep 04 '25 05:09

Patrick