Reputation: 3728
I'm trying to fetch person details, where middle name is missing some times, in my application. I'm trying with like this:
contactTable.Select(c => c.Title + " " + c.FirstName).ToList();
But whenever the title column remains null in DB, it returns empty for that entry. I want some kind of like:
contactTable.Select(c => (string.IsNullOrEmpty(c.Title) ? "" : c.Title + " ") + c.FirstName).ToList();
Is this possible in one linq statement? Thanks in advance.
This is possible and the complete answer is including the nullable MiddleName:
contactDetails = contactTable.Select(c =>
((c.Title ?? "") + " " + c.FirstName).Trim() + " " + ((c.MiddleName ?? "") + " " + c.LastName).Trim()).ToList();
See the double use of Trim()
.
Upvotes: 2
Views: 2849
Reputation: 176896
Make use of : ?? Operator
try this below code
contactTable.Select(c => ( (( c.Title ?? "") + " " + c.FirstName).Trim()).ToList();
Upvotes: 3